python - Django 在单个查询集中组合外键

标签 python django postgresql django-models django-queryset

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

我正在寻找一种方法来为此类的所有对象创建单个查询集,这些对象根据某些条件被其他类引用为 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)

关于python - Django 在单个查询集中组合外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49241246/

相关文章:

python - 使用 py.test 打印测试执行时间并锁定慢速测试

python - 从头开始进行交叉验证

python - 使用 Hugging Face Transformers 库你怎么能 POS_TAG 法语文本

python - 使用 type() 定义类对象 : Why can't I use the name of an attribute meant to be deepcopied?

PostgreSQL:如何捕获函数中的异常?

python - 在映射函数的列表推导式中传递命名参数

django - 如何在 Django 中自动创建 utf8 slug?

python - 无法在 Django 中加载 .css 和图像文件

ruby-on-rails - Heroku 页面 :backups restore fail due apparently to Rails application timeout

ruby-on-rails - Postgresql 无法加载 hstore.so