Answer the question
In order to leave comments, you need to log in
Why does a field with an associated category return None?
The essence of the question is that when calling the model in django views, I want to display the category or categories associated with the product.
The product is associated with the category by such a link:
category = models.ManyToManyField(Category, null=True, blank=True)
tv= Tovar.objects.filter(id = 1)
for item in tv:
category = item.category
print(category.name)
Answer the question
In order to leave comments, you need to log in
The Many to Many relationship is designed to store many objects, as its name suggests, not just one. Therefore, the category field stores not one category that has a name field, but a relation manager that allows you to get a set of categories:
tv = Tovar.objects.filter(id = 1)
for item in tv:
for category in item.category.all():
print(category.name)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question