D
D
Dmitry Ivanov2018-02-13 20:09:22
Django
Dmitry Ivanov, 2018-02-13 20:09:22

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)

View code:
tv= Tovar.objects.filter(id = 1)
for item in tv:
    category = item.category
    print(category.name)

Why is the value None in the console instead of the product category, but in the django admin panel everything works and is displayed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-13
@DmitrIvanov

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 question

Ask a Question

731 491 924 answers to any question