Django在单个查询中组合外键

2024-04-26 20:54:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

谢谢你的时间。在


Tags: 对象模型modelobjectsmodelsyearclassauthor
3条回答

也可以通过以下方式实现:

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




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

您将在Person上为Books和MusicAlbums创建一个^{}模型实例。由于您没有重写它们,它们可能仍然具有默认名称book_set和{}。在

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

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

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

^{pr2}$

我现在还没有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)

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

^{pr2}$

相关问题 更多 >