[Answer]-Django ManyToManyField on multiple attributes of multiple class

1👍

You can have multiple M2M with the same class, you just have to add a related_name parameter like so:

class Recommendation(models.Model):
    preference_type = models.ManyToManyField('Person_Preference', related_name='foo')
    preference_value = models.ManyToManyField('Person_Preference', related_name='bar')
    ...

EDIT

For your situation, just do this:

class Recommendation(models.Model):
    #I believe convention for m2m is to pluralize the field name
    preferences = models.ManyToManyField('Person_Preference')

Your query would be:

Recommendation.objects.filter(preferences__type='luxury', preferences__value='cooling')

EDIT 2

Here is a more detailed example:

Models:

class Preference(CommonModel):
    type = models.CharField(max_length=250, null=True, blank=True)
    value = models.CharField(max_length=250, null=True, blank=True)

class Recommendation(CommonModel):
    name = models.CharField(max_length=250, null=True, blank=True)
    preferences = models.ManyToManyField(Preference, null=True, blank=True)

    def __unicode__(self):
        return self.name

In the Django shell:

p1 = Preference.objects.create(type='foo', value='bar')
p2 = Preference.objects.create(type='foo')
p3 = Preference.objects.create(value='bar')

r1 = Recommendation.objects.create(name='foobar')
r1.preferences.add(p1)
r2 = Recommendation.objects.create(name='foo')
r2.preferences.add(p2)
r3 = Recommendation.objects.create(name='bar')
r3.preferences.add(p3)

>>> Recommendation.objects.filter(preferences__type='foo')
[<Recommendation: foobar>, <Recommendation: foo>]

>>> Recommendation.objects.filter(preferences__value='bar')
[<Recommendation: foobar>, <Recommendation: bar>]

>>> Recommendation.objects.filter(preferences__type='foo', preferences__value='bar')
[<Recommendation: foobar>]
👤WBC

Leave a comment