Django tastypie中的非规范化模型
我试图做的是将查询结果从模型添加到modelresource,如您在这段代码中所见:Django tastypie中的非规范化模型,django,api,tastypie,denormalization,Django,Api,Tastypie,Denormalization,我试图做的是将查询结果从模型添加到modelresource,如您在这段代码中所见: def dehydrate(self, bundle): bundle.data['image'] = place_image.image.get(place=1).get(cardinality=0) 我想向PlaceResource添加一个字段,该字段将包含place_站点模型中的图像,其中place=1,基数=0。但我收到一个错误: The 'image' attribute can only
def dehydrate(self, bundle):
bundle.data['image'] = place_image.image.get(place=1).get(cardinality=0)
我想向PlaceResource添加一个字段,该字段将包含place_站点模型中的图像,其中place=1,基数=0。但我收到一个错误:
The 'image' attribute can only be accessed from place_image instances
所以,我的问题是:在tastypie modelresource中是否不可能使用来自另一个模型的查询结果?很抱歉我的英语不好,如果有什么问题请纠正我。谢谢你抽出时间。
下面是完整的代码:
型号。py:
class place(models.Model):
idPlace = models.AutoField(primary_key=True)
Name = models.CharField(max_length=70)
class place_image(models.Model):
idImage = models.AutoField(primary_key=True)
place = models.ForeignKey(place,
to_field='idPlace')
image = ThumbnailerImageField(upload_to="place_images/", blank=True)
cardinality = models.IntegerField()
API.py
from models import place
from models import place_image
class PlaceResource(ModelResource):
class Meta:
queryset = place.objects.all()
resource_name = 'place'
filtering = {"name": ALL}
allowed_methods = ['get']
def dehydrate(self, bundle):
bundle.data['image'] = place_image.image.get(place=1).get(cardinality=0)
return bundle
class PlaceImageResource(ModelResource):
place = fields.ForeignKey(PlaceResource, 'place')
class Meta:
queryset = place_image.objects.all()
resource_name = 'placeimage'
filtering = {"place": ALL_WITH_RELATIONS}
allowed_methods = ['get']
您得到的错误是由于您正在访问模型类的
image
属性而不是实例而导致的
在脱水
方法中正在脱水的对象存储在bundle
参数的obj
属性中。此外,通过访问place\u image
model类的image
属性,您试图将place\u image
模型过滤到只有place=1
和cardinality=0
的模型。由于image
不是ModelManager
实例,这种过滤将无法工作。您应该使用对象
属性。此外,get()
方法返回实际的模型实例,因此对get()
的后续调用将引发AtributeError
,因为place\u image
模型实例没有属性get
总之,你的脱水剂应该是这样的:
def dehydrate(self, bundle):
bundle.data['image'] = place_image.objects.get(place_id=1, cardinality=0).image
return bundle
请注意,此代码需要place\u图像
和所需的值存在,否则将抛出place\u图像.DoesNotExist
您的模型中还存在一些冗余:
和idPlace
可以删除,因为django默认创建一个idImage
,当没有定义其他主键字段时,该字段是名为AutoField
的主键id
字段有一个冗余的place\u image.place
参数,因为默认情况下to\u字段
指向主键字段ForeignKey