在Django中纠正不正确的序列化

b09cbbtk  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(144)

序列化后,我尝试通过连接3个表来调用Django-rest API,然后我得到了问题原始异常文本是:* 由于'Store'对象没有属性'Storeimage'.**,我希望通过连接3个模型来获得API。
我的模特

class Store(models.Model):
    user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL)
    address = models.ForeignKey(Address, null=True,on_delete=models.CASCADE)
    store_name = models.CharField(max_length=255)
    store_about = models.CharField(max_length=255,null=True)
    store_location = models.CharField( max_length=255)
    #store_address = models.TextField()
    store_phoneno = models.CharField(max_length=12)


class Storeimage(models.Model):
    store = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL)
    picture = models.ImageField(upload_to='store_image/%Y/%m/',max_length=255,null=True)

class Address(models.Model):
    street = models.TextField()
    country = models.ForeignKey(Country, default=1,null=True,  on_delete=models.CASCADE)
    state = models.ForeignKey(State, default=1,null=True, on_delete=models.CASCADE)

字符串
我的serilzation

class StoreGetSerialiser(serializers.ModelSerializer):
    #store_product = StoreproductSerializer(many=True)
    address = AddressSerializer()
    Storeimage = StoreImage(many=True)
    owner = UserPublicSerializer(source='user', read_only=True)
    class Meta:
        model = Store

        fields = [
            'pk',
            'owner',
            'store_name',
            'Storeimage',
            'store_location',
            'address',
            'store_phoneno',
            'store_website',

        ]

class StoreImage(serializers.ModelSerializer):
    class Meta:
        model = Storeimage
        fields = '__all__'


我的预期输出:

{
        "pk": 2,
        "owner": {
            "id": 1
        },
        "store_name": "",
        "store_location": "",
        "address": {
            "id": 14,
            "street": "1",
            "country": 1,
            "state": 1,
            "city": 1
        },
        "store_phoneno": "",
        "store_image": [{"pk":1,"picture":"/location/abcd"},{"pk":2,"picture":"/location/abcd"}]
    },

x759pob2

x759pob21#

Storeimage是型号Store的错误名称。用户storeimage_set改为:

class StoreGetSerialiser(serializers.ModelSerializer):
    ...
    storeimage_set = StoreImage(many=True)

    class Meta:
        model = Store
        fields = [
            'pk',
            'owner',
            'store_name',
            'storeimage_set',
            'store_location',
            'address',
            'store_phoneno',
            'store_website',

        ]

字符串
另外请注意,您可以在FK字段中使用related_name自定义此字段名称。

相关问题