Django在单个查询集中组合外键 [英] Django combine foreign keys in a single queryset

查看:174
本文介绍了Django在单个查询集中组合外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django应用程序中有一个模型,该模型被其他多个模型引用为外键。

I have a model in a Django application that is being referenced by multiple other models as a ForeignKey.

我正在寻找一种创建对象的方法。 单个查询集,该类的所有对象根据某些条件被其余类引用为ForeignKey。

What I am looking for is for a way to create a single queryset for all objects of this class that are being referenced as ForeignKey by the rest of the classes based on some criteria.

我不是即使可以确定是否可行,但我还是想问问。

I am not even sure if this is possible, but I thought about asking anyway.

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,但是类似这样的事情:

I don't have Django in front of me at the moment, but what about something like:

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)

或者,如果您仍然必须进行前两个查询,

Or, if you have to do those first two queries anyway,

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

这篇关于Django在单个查询集中组合外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆