DRF在序列化器中使用另一个与模型相关的字段

时间:2018-03-27 11:46:24

标签: python django django-rest-framework

我有3个型号产品 - Peyment - ProductDiscountControll

PeymentProductDiscountControll与列" product"有关系到产品

我希望在获取请求时在peyment serilizer中提供相关的ProductDiscountControll数据,例如discountdiscount_code_precent

为了做到这一点,我尝试在Serializer

中使用代码
def get_product_discount(self, obj):
    return obj.product.product_discount.discount

但是服务器说:

Field name `product_discount` is not valid for model `Peyment`.

我也是这样尝试的:

product_discount = ProductDiscountControllSerializer(many=True,read_only=True)

product_discount在结果中不可用

我的观点看起来像这样

class PeymentAPIView(APIView, mixins.DestroyModelMixin):
    permission_classes = [IsSafeGuard]

    def get(self, request):
        pay = Peyment.objects.filter(
            email=request.user.email,
            status=0,

        )
        serializer = PeymentSerializer(instance=pay, many=True)
        return Response(serializer.data)

这是获取请求的相关Serializer类:

class PeymentSerializer(ModelSerializer):
    producttitle = serializers.SerializerMethodField()

    def get_producttitle(self, obj):
        return obj.product.title

    productprice = serializers.SerializerMethodField()

    def get_productprice(self, obj):
        return obj.product.price


    def get_discount(self, obj):
        return obj.product_discount.discount
    #product_discount = ProductDiscountControllSerializer(many=True,read_only=True)


    class Meta:
        model = Peyment
        fields = [
            'product',
            'id',
            'producttitle',
            'productprice',
            'discount',
            'status',
            'user',
            'email',
            'transfer_id',
            'created_date',
            'updated_date',
        ]
        read_only_fields = ['email', 'user', 'producttitle', 'productprice']

这是产品型号:

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True)
    title = models.CharField(max_length=200)
    video_length = models.CharField(max_length=20, null=True, blank=True)
    mini_description = models.CharField(max_length=1000, null=True, blank=True)
    full_description = models.TextField(null=True, blank=True)
    you_need = models.CharField(max_length=1000, null=True)
    you_learn = models.CharField(max_length=2000, null=True)
    price = models.CharField(max_length=50, null=True, blank=True)
    video_level = models.CharField(max_length=100, null=True, blank=True)
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)
    image = models.FileField(upload_to=upload_to_custom_p,null=True,blank=True)

Peyment模型:

class Peyment(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id',
                                related_name='product_peyment')
    status = models.CharField(max_length=30, null=True)
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    transfer_id = models.CharField(max_length=100, null=True, blank=True)
    email = models.EmailField()
    created_date = models.DateTimeField(auto_now_add=True)
    updated_date = models.DateTimeField(auto_now=True)

和折扣模型:

class ProductDiscountControll(models.Model):
    product = models.OneToOneField(Product, on_delete=models.CASCADE, to_field='product_id',
                                related_name='product_discount')
    discount = models.IntegerField(max_length=50, null=True, blank=True)
    discount_code = models.CharField(max_length=50, null=True, blank=True)
    discount_code_precent = models.CharField(max_length=80, null=True, blank=True)
    updated_date = models.DateTimeField(auto_now=True)

更新:

# product peyment
class PeymentSerializer(ModelSerializer):
    producttitle = serializers.SerializerMethodField()

    def get_producttitle(self, obj):
        return obj.product.title

    productprice = serializers.SerializerMethodField()

    def get_productprice(self, obj):
        return obj.product.price

    def get_discount(self, obj):
        serializer = ProductDiscountControllSerializer(obj.product.product_discount)
        return serializer.data


    class Meta:
        model = Peyment
        fields = [
            'product',
            'id',
            'producttitle',
            'productprice',
            'discount',
            'status',
            'user',
            'email',
            'transfer_id',
            'created_date',
            'updated_date',
        ]
        read_only_fields = ['email', 'user', 'producttitle', 'productprice']

1 个答案:

答案 0 :(得分:3)

您只需在序列化程序的方法中使用product.product_discount字段名称即可。要返回序列化数据,您应将此值传递给ProductDiscountControllSerializer并返回serializer.data

def get_discount(self, obj):
    discount = getattr(obj.product, 'product_discount', None)
    if discount: 
        serializer = ProductDiscountControllSerializer(discount)
        return serializer.data 
    return None

UPD

您应该在序列化程序中使用discount明确声明SerializerMethodField字段,以便在fileds列表中使用它:

class PeymentSerializer(ModelSerializer):
    discount = serializers.SerializerMethodField()
相关问题