django:具有多对多字段的查询模型

时间:2022-02-16 20:13:27

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.

这里主题的价值是相关主题id的列表。这给了我一个错误,说参数应该是字符串或数字是TypeError。

How can I handle this situation with multiple subjects ?

如何处理多个科目的这种情况?

1 个解决方案

#1


1  

You use the __in operator

您使用__in运算符

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而不是其中任何一个,我们可以使用Q对象

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.

请注意,任何运算符都在逻辑上适合get_or_create,因为没有足够的信息可以创建,因此您可能需要将其拆分。

#1


1  

You use the __in operator

您使用__in运算符

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而不是其中任何一个,我们可以使用Q对象

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.

请注意,任何运算符都在逻辑上适合get_or_create,因为没有足够的信息可以创建,因此您可能需要将其拆分。