我要做的是将模型中的查询结果添加到模型资源中,正如您在这段代码中看到的那样:
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']