如何过滤多对多的fj?django

时间:2017-05-27 10:01:58

标签: django django-rest-framework manytomanyfield

示例:

class Person(model.Models)
  name = model.CharField(max_length=30)
  age = model.IntegerField()
class Book(model.Model)
  title = model.CharField(max_length=30)
  author = model.ManyToManyField(Person)

per1 = Person('Jack',10)
per1.save
per2 = Person('Rose',20)
per2.save
book1 = Book()
book1.title = 'booktitle'
book1.author.add(per1)
book1.author.add(per2)

现在我想得到像这样的'book1'obj

{
  'title':'booktitle',
  'author':[
       {
         'name':'Jack',
         'age':10,
      }
   ]
}

'book1'obj中只有一位作者 如何过滤相关领域? 有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以使用:

Book.objects.filter(author="Jack").all()

您还可以过滤多位作者:

Book.objects.filter(author=["Jack", "Rose"]).all()