如何仅使用django获取请求中的外键字段

时间:2019-01-14 09:15:22

标签: django django-models django-rest-framework django-views

我有这样的模型:

class Image(models.Model):
    name=models.CharField(max_length=40,unique=False)
    image=models.ImageField(upload_to='photos/%Y/%m/%d')

class Resized_image(models.Model):
    image = models.ForeignKey(Image, related_name='resized_images', on_delete=models.CASCADE)
    rendition = models.ForeignKey(Rendition,related_name='rendition_id',on_delete=models.CASCADE)
    path = models.CharField(max_length=256,unique=False)

我在Resized_image模型中将Image表的imagefield指定为外键,所以如果获取请求我也应该在Resized_image表中获得该路径,我该怎么办?

当我触发图像获取请求时,我将得到如下输出:

{
            "id": 1,
            "name": "xyz1",
            "image": "http://10.75.12.175:7010/photos/2019/01/10/73440005-078.jpg"
}

但是我想要在Resize_image路径内也获取请求

我正在序列化器中尝试这样:

class resized_imagesSerializer(serializers.ModelSerializer):
     class Meta:
         model = Resized_image
         fields = ('path',)
        read_only_fields = ['path']

class imagesSerializer(QueryFieldsMixin,serializers.ModelSerializer):
        resized_images = resized_imagesSerializer(many=True,required=False)
        class Meta:
        model = Image
        fields = ('id','name','image','resized_images')
        read_only_fields =['resized_images']

如果即使在发布请求中也尝试这样做,我会得到这个resized_images字段。有什么办法解决吗?

1 个答案:

答案 0 :(得分:0)

您可以通过ImageField访问<field_name>.url网址。如果aResized_image的实例,则a.image.url是您的图片网址。因此,您可以使用save方法获取网址。

class Resized_image(models.Model):
    image = models.ForeignKey(Image, related_name='resized_images', on_delete=models.CASCADE)
    rendition = models.ForeignKey(Rendition,related_name='rendition_id',on_delete=models.CASCADE)
    path = models.CharField(max_length=256,unique=False)

    def save(self, *args, **kwargs):
        self.path = self.image.url
        super().save(*args, **kwargs)