wrufesh
wrufesh

Reputation: 1406

django: quering model with many-to-many fields

I have models like this

class Book(models.Model):
    title = models.CharField(max_length=254)
    subtitle = models.CharField(max_length=254, null=True, blank=True)
    subjects = models.ManyToManyField(Subject)

class Subject(models.Model):
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=254, null=True, blank=True)

Now when i do

Book.objects.get_or_create(subjects=[2,4] , title='Genetics', subtitle='Theory of Genetics')

Here the value of subjects is the list of related subjects id. This gives me an error saying arguments should be string or number a TypeError.

How can I handle this situation with multiple subjects ?

Upvotes: 0

Views: 35

Answers (1)

krs
krs

Reputation: 4154

You use the __in operator

Book.objects.filter(subjects__in=[2,4])

It can also be used with a queryset

Book.objects.filter(
     subjects__in=Subject.objects.filter(name__contains="interesting"))

If you instead want Book with both subjects and not just any of them we can use the Q object

Book.objects.filter( Q(subject__in=[2]) & Q(subject__in=[4]) )

Note that the any of operators doest logically fit in to a get_or_create because there isnt enough information to create so you might have to split it up.

Upvotes: 1

Related Questions