Having a problem with a M2M related queryset: simplified model is
class Category(models.Model):
name = models.CharField(max_length=200)
class Product(models.Model):
name = models.CharField(max_length=200)
category = models.ManyToManyField(
Category, blank=True, null=True, related_name="categorytest")
I usually do related queries using related name (which works fine here no problem) yet I wanted to try "set_all()" in this case.
Say I do:
elecs = Category.objects.get(name="Electronics")
then:
elecs.product_set.all()
I get AttributeError: 'Category' object has no attribute 'product_set'. I am a bit surprised because this is an error that happens when using a queryset instead of a model instance yet, if a confirmation was needed, a type(elecs) gives me <class 'store.models.Category'>.
I migrated/erased db multiple times, no change.
Any idea ? Thanks
CodePudding user response:
You specify the name of the relation in reverse with the related_name=…
parameter [Django-doc]. Since you set related_name='categorytest'
, you thus access these with:
elecs.categorytest.all()
But likely using categorytest
is not a good idea. It might be better to specify this for example as related_name='products'
.