Django tastypie中的非规范化模型

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

我试图做的是将查询结果从模型添加到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 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
    idImage
    可以删除,因为django默认创建一个
    AutoField
    ,当没有定义其他主键字段时,该字段是名为
    id
    的主键
  • place\u image.place
    字段有一个冗余的
    to\u字段
    参数,因为默认情况下
    ForeignKey
    指向主键字段

工作正常+很好的解释,谢谢!关于冗余,你是对的,但我喜欢显式,因为python的zen说显式是一回事,编写代码让其他人想知道为什么作者显式传递默认参数是另一回事:P