繁体   English   中英

Django将外键组合在一个查询集中

[英]Django combine foreign keys in a single queryset

我在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`?

谢谢你的时间。

我现在面前没有Django,但是有什么:

class Person(models.Model):
    pass


class Book(models.Model):
    year_published = models.PositiveIntegerField()
    author = models.ForeignKey(Person, related_name='books')


class MusicAlbum(models.Model):
    year_published = models.PositiveIntegerField()
    producer = models.ForeignKey(Person, related_name='albums')

Person.objects.filter(books__year_published__gte=2018, albums__year_published__gte=2018)

或者,如果你不得不做前两个查询,

Person.objects.filter(books__in=recent_books, albums__in=recent_music_albums)

您将有Person模型实例一RelatedManagerBook S和MusicAlbum秒。 可能他们仍然会有默认名称book_setmusicalbum_set因为你没有覆盖它们。

您可以使用这些来查找与一个人实例关联的书籍/音乐专辑:

persons_books = person.book_set.all()
persons_musicalbums = person.musicalbum_set.all()

同样,您可以从模型管理器生成相关的查询集:

qs = Person.objects.exclude(book=None).exclude(musicalbum=None)

同样可以通过以下方式实现:

person = Person.objects.latest('book__year_published', 'musicalbum__year_published')

要么

personList = Person.objects.all().order_by('-book__year_published', '-musicalbum__year_published')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM