[Answer]-Django Multiple Foreign key set_all in template

1👍

You are trying to do it the other way round. As the django documentation states:

Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Blog object b has access to a list of all related Entry objects via the entry_set attribute: b.entry_set.all().

Notice the "other" side.

So in your case you can do state.customer_set.all(). But looking at what you are trying to achieve I guess you are using the wrong field type, If you want the customer to be able to choose multiple location you should instead use ManyToManyField.

class Customer(models.Model):
    shop = models.ForeignKey(Shops)
    user = models.ForeignKey(User)
    uuid = UUIDField(auto=True)
    name = models.CharField(max_length=200)
    countries = models.ManyToManyField(Country)
    states = models.ManyToManyField(States)
    cities = models.ManyToManyField(Cities)

and then you can do something like customer.countries.all() or customer.states.all() or customer.cities.all()

Update: Adding data to ManyToManyField:

To add data to ManyToManyField‘s you can do something like this:

customer = Customer(shop_id=shop_id, name=name)
customer.save()

# Add ManyToMany's
custome.states.add(state)
customer.cities.add(cities)
customer.countries.add(country)

I would also suggest you to go through the django documentation for ManyToManyFields

👤Amyth

Leave a comment