我有看起來像這樣的 Django 模型
class Customer(models.Model):
name = models.CharField(_("Name"))
class Feature(models.Model):
label = models.CharField(_("Name"))
class AddOn(models.Model):
customer = models.ForeignKey(Customer)
feature = models.ForeignKey(Feature)
鑒于我有一個客戶實體,例如
customer = Customer.objects.get(pk=1)
如何在一次查詢中獲取特征中的所有標簽以避免 N 1 查詢?
現在我所做的是:
[addon.feature.label for addon in self.addon_set.all()]
但我認為addon.feature如果有很多插件,每個都會創建一個不是很優化的查詢
uj5u.com熱心網友回復:
您可以使用values / values_list在單個查詢中獲取所有標簽
self.addon_set.values_list('feature__label', flat=True)
編輯:ManyToManyField 示例
class Customer(models.Model):
name = models.CharField(_("Name"))
features = ManyToManyField('Feature', through='AddOn')
class Feature(models.Model):
label = models.CharField(_("Name"))
class AddOn(models.Model):
customer = models.ForeignKey(Customer)
feature = models.ForeignKey(Feature)
然后,您可以執行類似customer_obj.features.all()or 的查詢feature_obj.customers.all(),這不會影響您仍然查詢 AddOn 模型的能力
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/420706.html
標籤:
