我在Django应用程序中有一个模型,它被其他多个模型作为ForeignKey引用。在
我在寻找一种方法,为这个类的所有对象创建一个单个查询集,这些对象被其他类基于某些条件作为ForeignKey引用。在
我甚至不知道这是否可能,但我还是想问问。在
class Person(models.Model):
pass
class Book(models.Model):
year_published = models.PositiveIntegerField()
author = models.ForeignKey(Person)
class MusicAlbum(models.Model):
year_published = models.PositiveIntegerField()
producer = models.ForeignKey(Person)
recent_books = Book.objects.filter(year_published__gte=2018)
recent_music_albums = MusicAlbum.objects.filter(year_published__gte=2018)
# How can I create a **single** queryset of the Person objects that are being referenced as `author` in `recent_books` and as `producer` in `recent_music_albums`?
谢谢你的时间。在
也可以通过以下方式实现:
person = Person.objects.latest('book__year_published', 'musicalbum__year_published')
或
personList = Person.objects.all().order_by('-book__year_published', '-musicalbum__year_published')
您将在} 模型实例。由于您没有重写它们,它们可能仍然具有默认名称}。在
Person
上为Book
s和MusicAlbum
s创建一个^{book_set
和{您可以使用这些来查找与一个人实例关联的书籍/音乐专辑:
同样,您可以从模型管理器生成相关的查询集:
^{pr2}$我现在还没有Django在我面前,但是像这样的东西呢:
或者,如果你要做前两个查询
^{pr2}$相关问题 更多 >
编程相关推荐