使用通用关系处理项目的图像和文件

时间:2019-03-24 16:19:33

标签: django-rest-framework

我的问题是我了解如何使用通用关系,但无法在序列化程序中上传多个图像时执行它

我试图在上载项目的媒体(文件或图像)中使用通用关系,但是没有运气,我不知道如何制作序列化程序,我试图以书签和有标记的项目为例,但是仍然很困惑< / p>


class ImageHandler(models.Model):
    file = models.FileField(blank=True,upload_to='images/')
    image = models.ImageField(blank=True,upload_to='images/')
    TYPE_CHOICES    =   (
        ('files',   'Files'),
        ('images',  'Images'),
    )
    file_type   =   models.CharField(max_length=10,
            choices=TYPE_CHOICES,
            )
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()



class Branch(models.Model):
    title = models.CharField(max_length=100)
    phone = models.CharField(max_length=30,unique=True,null=False)
    company = models.ForeignKey(CompanyData,related_name='company_branch',on_delete=models.CASCADE)
    location = models.CharField(max_length=230)
    status  =   models.BooleanField(default=True)
    created_at  =   models.DateTimeField(auto_now_add=True)
    updated_at  =   models.DateTimeField(auto_now=True)
    images = GenericRelation(ImageHandler)
class ImageObjectRelatedField(serializers.RelatedField):
    def to_representation(self, value):
        if isinstance(value, Branch):
            serializers = ImageSerializer
            # serializer = BranchSerializer(value)
        else:
            raise Exception('Unexpected type of tagged object')

        return serializer.data

class BranchSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only = True)

    images = ImageObjectRelatedField(many=True, queryset=ImageHandler.objects.all())
    company = serializers.PrimaryKeyRelatedField(queryset=CompanyData.objects.all())
    class Meta:
        model = Branch
        fields = ('id','title','phone','location','company','status','images')

我希望上传与特定型号相关的多个图像或文件

0 个答案:

没有答案