Please tell me how to display the contents of the many-to-many link in the template. For example, there is a model:

class Variety(models.Model): varietyName = models.CharField(max_length=30) def __str__(self): return self.varietyName class Fruits(models.Model): fruitName = models.ManyToManyField(Specs) def __str__(self): return self.fruitName 

I created the record "Apples" in the table "Fruits", in the table "Variety" I created types of apples (red, green, rotten, etc.) and connected with "Apples" in the table "Fruits". How now is all the right to transfer to the template and display?

To preamera in view.py there is a function, which is triggered when entering the main page. I understand that the values ​​need to pass so?

 def index(request): return render(request, 'index.html', {'fruits': Fruits.objects.all()}) 

If so, how do you get the types of apples in the template?

  • you have models of Variety and Fruits not connected to each other - Sergey Chabanenko
  • return "self.fruitName" do not write this way, it is not logical at first, secondly it is wrong. - Sergey Chabanenko

1 answer 1

If you upgrade your model a bit, to the following:

 class Variety(models.Model): varietyName = models.CharField(max_length=30) def __str__(self): return self.varietyName class Fruits(models.Model): name = models.CharField(max_length=255) variety = models.ManyToManyField(Variety) def __str__(self): return self.name 

then you can unload related objects. Notice that I changed the __str__ method. It is not logical to return a string representation of a group of objects.

In views, everything is fine; in the template, you can display the values ​​in a cycle by fruit and each fruit can upload a list of its species. Example:

 {% for fruit in fruits %} <h5>{{ fruit.name }}</h5> // название фрукта {% for v in fruit.variety.all %} <h5>{{ v.varietyName }}</h5> // название вида {% endfor %} {% endfor %} 

For a more detailed description, you can refer to the documentation.

  • Yes thank you. At the expense of str - this is not a deliberate error, copied your code and forgot to change the string, and there it is the string + the value of the variable is returned. - FWO
  • By the way, to optimize such a query can see prefetch_related . - Sergey Chabanenko