Django将模型实例和查询集序列化在一起

时间:2017-01-27 06:47:17

标签: jquery python django

因此;

我试图将django queryset和django模型实例序列化,以便我可以在template.html中使用它们的值,如下所示:

# model.py
class PlotManagement(models.Model):
    farm = models.ForeignKey(Farm,verbose_name='FieldID')
    plotID = models.ForeignKey(Plot,verbose_name='PlotID')
    crop = models.ManyToManyField(Crop,verbose_name='Crop Name')
    cropping_system = models.CharField('Cropping System',max_length=20)

# function.py(where i serialize)
def plotmanagement_info(request,farm,plot):
    plotmanagement_instance = PlotManagement.objects.get(plotID__pk=plot,farm=farm)
    plot_cropping_system = plotmanagement_instance.cropping_system
    crops = plotmanagement_instance.crop.all()
    plotmanagement_info = [plot_cropping_system,crops]
    return HttpResponse(json.dumps(plotmanagement_info),content_type="application/json")

我得到的错误是:

[<Crop: Bell pepper>, <Crop: Head cabbage>] is not JSON serializable

是否可以使用字符串模型实例序列化manytomany queryset

>>>type(plot_cropping_system)
>>><class 'str'>
>>> type(crops)
<class 'django.db.models.query.QuerySet'>

1 个答案:

答案 0 :(得分:0)

如果这是一次性事情,那么有一些方法你可以在没有任何依赖的情况下解决这个问题,否则我会建议你研究一下django-rest-framework

在模型定义中添加方法to_json并修改您的视图。

class Crop(models.Model):
    title = models.CharField(max_length=20)

    def to_json(self):
        return {"title":self.title,"field_1":field_2, "field_2":field_2}

# function.py(where i serialize)
def plotmanagement_info(request,farm,plot):
    plotmanagement_instance = PlotManagement.objects.get(plotID__pk=plot,farm=farm)
    plot_cropping_system = plotmanagement_instance.cropping_system
    crops = plotmanagement_instance.crop.all()
    plotmanagement_info = [plot_cropping_system,[crop.to_json() for crop in crops]]
    return HttpResponse(json.dumps(plotmanagement_info),content_type="application/json")

这只是一种快速的方法。