Django 带有型号为dict(自)的多功能域
不确定标题是否正确,抱歉给您带来不便 使用下面的代码中的model_to_dict()将ManyToManyField从模型发送到字典时遇到问题 型号.pyDjango 带有型号为dict(自)的多功能域,django,dictionary,django-models,Django,Dictionary,Django Models,不确定标题是否正确,抱歉给您带来不便 使用下面的代码中的model_to_dict()将ManyToManyField从模型发送到字典时遇到问题 型号.py from django.db import models from django.forms import model_to_dict from app_1.models import * class Stuff(models.Model): thing_1 = models.CharField(max_length=100, n
from django.db import models
from django.forms import model_to_dict
from app_1.models import *
class Stuff(models.Model):
thing_1 = models.CharField(max_length=100, null=True, blank=True)
thing_2 = models.ManyToManyField(OtherStuff, blank=True, related_name="thing")
def toJSON(self):
item = model_to_dict(self)
item['thing'] = self.thing.toJSON()
return item
当我运行查询并加载我的Stuff模型时,出现以下错误:
from app_2.models import *
s = Stuff.objects.get(pk=1)
# here is where I send my model to a dictionary
s.toJSON()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "P:\test\app\app_2\stuff\models.py", line 10, in toJSON
return item
AttributeError: 'ManyRelatedManager' object has no attribute 'toJSON'
来自app_2.models导入*
s=Stuff.objects.get(pk=1)
#这是我把模型送到字典的地方
s、 toJSON()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“P:\test\app\app\u 2\stuff\models.py”,第10行,在toJSON中
退货项目
AttributeError:'ManyRelatedManager'对象没有属性'toJSON'
我遇到过多种将ManyToManyField发送到字典的方法,但是,没有一种方法使用模型_to_dict()。由于使用简单,我想使用此方法。使用此方法,您需要使用以下语法:
item['thing'] = [t.toJSON() for t in self.thing_2.all()]
另外,为OtherStuff
模型实现toJSON
方法
或者您也可以使用model\u对OtherStuff
进行记录:
def toJSON(self):
item = model_to_dict(self)
item['thing'] = [model_to_dict(t) for t in self.thing_2.all()]
return item