Django Shortcut nested foreign key(Django快捷方式嵌套外键)
问题描述
假设我的models.py中有以下内容:
Suppose I have the following in my models.py:
class Book:
pass
class Part:
book = models.ForeignKey(Book)
class Chapter:
part = models.ForeignKey(Part)
number = models.IntegerField()
我想做
book = Book.objects.get(id=someID)
chapters = Book.chapters.get(number=4)
这样做的干净方法是什么?我想到了书籍类的经理,但它似乎不适用于这种情况.
What is a clean way to do so? I thought of a Manager on the book class but it doest not seem to work for this case.
当然我可以在课本上实现一个 get_chapters 方法,但我想避免这种情况.
Of course I could implement a method get_chapters on class book but i would like to avoid this.
有什么想法吗?
推荐答案
对 FK 字段使用 related_name 参数,并为查询集使用 prefetch_related,将允许您以最小的性能损失获取与书籍相关的所有信息(每个 prefetch_related 参数调用单独的查询).
Using related_name arguments for FK fields, coupled with prefetch_related for a queryset, will allow you to fetch all info related to a book with minimal performance hit (each prefetch_related param calls a separate query).
class Book:
pass
class Part:
book = models.ForeignKey(Book, related_name="parts")
class Chapter:
part = models.ForeignKey(Part, related_name="chapters")
number = models.IntegerField()
# fetch a book and all related info w/ only 2 db hits
book = Book.objects.first().prefetch_related("parts","parts__chapters")
print(book.parts.all()) # returns all parts for book
for part in book.parts.all():
print part.chapters.all()
您也可以在模板中执行此操作.
You can do this in a template as well.
然而,为了获得最高性能的解决方案,也可以从章节中保存 FK 以进行预订.这可以通过覆盖 save 方法轻松完成.
However, for the most performant solution, save a FK to book from chapter as well. This can be easily done by overriding the save method.
class Chapter:
part = models.ForeignKey(Part, related_name="part_chapters")
number = models.IntegerField()
book = models.ForeignKey(Book, related_name="chapters", null=True, blank=True) # allow null/blank values; will be populated in save method
def save(self, *args, **kwargs):
self.book = self.part.book
super(Chapter, self).save(*args, **kwargs)
>>> book = Book.objects.first().prefetch_related("parts","chapters")
>>> print(book.parts.all()) # returns all parts for book
>>> print(book.chapters.all())
这篇关于Django快捷方式嵌套外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django快捷方式嵌套外键
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01