来自两个相关表的Django嵌套列表

我在Django的models.py中有两个具有一对多关系的模型:

class Parcel(models.Model):
    farmer = models.CharField(max_length=200)
    name = models.CharField(max_length=200)
    area = models.FloatField()

class Crop(models.Model):
    parcel = ForeignKey(Parcel,on_delete=models.CASCADE)
    code = models.CharField(max_length=20)
    date_planted = models.DateTimeField()
    date_harvested = models.DateTimeField()

在一个包裹上,多年种植了多种农作物。裁剪通过ForeignKey与宗地相关。现在,我需要显示所选农民的所有地块和农作物的嵌套列表,例如:

[{ name: "parcel one",area: 22.2,crops: [{"code": "wheat",planted: "2017-01-01",harvested: "2018-09-12"},{"code": "maize",planted: "2019-04-03",harvested: "2019-09-09"}]
 },{ name: "parcel two",area: 11.7,harvested: "2019-09-09"},{"code": "wheat",planted: "2019-09-19",harvested: None}]
 }]

现在,我正在使用以下循环检索选定农民的所有地块和农作物的列表:

from django.forms.models import model_to_dict
from .models import Parcel
from .models import Crop

parcel_queryset = Parcel.objects.filter(farmer="John Smith") 
filtered_parcel_list = []
for parcel in parcel_queryset:
    parcel_dict = model_to_dict(parcel)
    parcel_dict["crops"] = list(parcel.crop_set.all().values())
    filtered_parcel_list.append(parcel_dict)

但是,如果有很多包裹,我的查询似乎很慢。我怀疑Django在我的for循环中使用每个parcel.crop_set.all().values()语句向数据库发送新查询。

有什么办法可以简化查询?如果可能的话,我想摆脱for loop并减少发送到数据库的SQL查询的数量。

wangzhenhxy 回答:来自两个相关表的Django嵌套列表

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3132812.html

大家都在问