我在 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/