【问题标题】:Denormalizing models in tastypie美味派中的非规范化模型
【发布时间】:2013-10-08 15:47:47
【问题描述】:

我要做的是将模型中的查询结果添加到模型资源中,正如您在这段代码中看到的那样:

def dehydrate(self, bundle):
    bundle.data['image'] = place_image.image.get(place=1).get(cardinality=0)

我想向 PlaceResource 添加一个字段,该字段将包含 place_site 模型中的图像,其中 place=1 和 cardinality=0。但我收到一个错误:

The 'image' attribute can only be accessed from place_image instances

所以,我的问题是:是否不可能在一个美味的模型资源中使用来自另一个模型的查询结果?对不起,我的英语不好,如果有什么问题,请纠正我。谢谢你的时间。 有完整的代码:

模型.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']

【问题讨论】:

    标签: django api tastypie denormalization


    【解决方案1】:

    您遇到的错误是由于您访问的是模型 classimage 属性,而不是 instance

    dehydrate 方法中脱水的对象存储在bundle 参数的obj 属性中。此外,您正在尝试通过访问 place_image 模型类的 image 属性将 place_image 模型过滤为仅具有 place=1cardinality=0 的模型。这种过滤将不起作用,因为 image 不是 ModelManager 实例。您应该改用 objects 属性。此外,get() 方法返回一个实际的模型实例,因此对 get() 的后续调用将引发 AtributeError,因为您的 place_image 模型实例没有属性 get

    所以,总而言之,您的dehydrate 应该是这样的:

    def dehydrate(self, bundle):
        bundle.data['image'] = place_image.objects.get(place_id=1, cardinality=0).image
        return bundle
    

    请注意,此代码要求存在具有所需值的 place_image,否则将抛出 place_image.DoesNotExist

    您的模型中也存在一些冗余:

    • idPlaceidImage 可以删除,因为 django 默认创建一个 AutoField,它是一个名为 id 的主键,而没有定义其他主键字段
    • place_image.place 字段有一个多余的to_field 参数,默认情况下ForeignKey 指向一个主键字段

    【讨论】:

    • 工作得很好+很好的解释,谢谢!关于冗余,你是对的,但我喜欢像 python 的禅宗所说的那样明确
    • 显式是一回事,编写代码让其他人想知道为什么作者显式传递默认参数是另一回事:P
    猜你喜欢
    • 2012-09-25
    • 2014-07-03
    • 2015-02-01
    • 2015-01-28
    • 2012-02-26
    • 1970-01-01
    • 2012-10-30
    • 2014-01-23
    • 1970-01-01
    相关资源
    最近更新 更多