为什么在发布外键时获取空值(当我在序列化器中使用slugrelatedfield获取外键作为字符串而不是整数时)

时间:2019-03-26 09:52:47

标签: django django-rest-framework

这是我的模特。py

app.Workbooks.Open("filename.xls", 2, True, None, None, "secret")

这是我的serializers.py

class Product(models.Model):
    product = models.CharField(max_length=200)
    def __str__(self):
         return self.product

class CustOrder(models.Model):
    CustomerName = models.CharField(max_length=200)
    email = models.EmailField(max_length=70,blank=True, null= True, unique= True)
    gender = models.CharField(max_length=6, choices=GENDER_CHOICES)
    phone = PhoneField(null=False, blank=True, unique=True)
    landmark = models.PointField()
    #landmark = models.TextField(max_length=400, help_text="Enter the landmark", default='Enter landmark')
    houseno = models.IntegerField(default=0)
    #product_name = models.CharField(max_length=200, choices=PRODUCT_CHOICES,default='Boneless chicken')
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True,related_name='production')
    quantity = models.IntegerField(default=0)
    price = models.ForeignKey(Price, on_delete=models.SET_NULL, null=True,related_name='pricetag')
    #price = models.DecimalField(max_digits=50, decimal_places=5, default=48.9)
    pay_method = models.CharField(max_length=200,choices=PAYMENT_CHOICES, default='RAZOR PAY')
    city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) 
    area = models.ForeignKey(Area, on_delete=models.SET_NULL, null=True)

    def __str__(self):
         return self.CustomerName

发布后的实际结果:

class CustOrderSerializer(serializers.ModelSerializer):

    class Meta:
        model = CustOrder
        fields = '__all__' 
    price = serializers.SlugRelatedField(read_only=True, slug_field='price')
    product = serializers.SlugRelatedField(read_only=True, slug_field='product')
    area = serializers.SlugRelatedField(read_only=True, slug_field='address')
    city = serializers.SlugRelatedField(read_only=True, slug_field='city')```

发布后的预期结果:

{
    "id": 7,
    "price": null,
    "product": null,
    "area": null,
    "city": null,
    "CustomerName": "tift",
    "email": "rkkk@gmail.com",
    "gender": "male",
    "phone": "(821) 699-7920, press 91",
    "landmark": "SRID=4326;POINT (0.04222869873046874 0.00102996826166618)",
    "houseno": 5,
    "quantity": 8,
    "pay_method": "cod"
}

1 个答案:

答案 0 :(得分:0)

如果要发布数据,则不能使这些字段为只读。您应该为每个SlugRelatedField提供一个查询集:

class CustOrderSerializer(serializers.ModelSerializer):

    class Meta:
        model = CustOrder
        fields = '__all__' 

    price = serializers.SlugRelatedField(slug_field='price', queryset=Price.objects.all())
    product = serializers.SlugRelatedField(slug_field='product', , queryset=Product.objects.all())