![](/img/trans.png)
[英]Django one to many relationship for API call in restframework using serializers
[英]How to implement One to many Relationship in Django RestFramework?
在這里我提到了我的model.py和serilaizers.py我想在這里使用一對多的概念。 我期待這樣的輸出。
預期產出
{
"id": 1,
"product_name": "Rice",
"description": "expired on 13-04-2018",
"sales": "55",
"cost": "55",
"tax_details": [
{
'id': 1,
'tax_name': "http://127.0.0.1:8000/tax/1/",
'percentage': 10
}, {
'id': 2,
'tax_name': "http://127.0.0.1:8000/tax/3/",
'percentage': 2
}, {
'id': 3,
'tax_name': "http://127.0.0.1:8000/tax/2/",
'percentage': 05
},
...
],
}
Models.py
TAX模型
這是主要的稅表這里我將維修稅名如(IGST,GST,VAT)這是一個下拉列表。
產品
這里包含產品詳細信息,我在預期輸出中提到過
TaxProduct
在此模型中,輸入的稅名和百分比應存儲單獨的模型。
class tax(models.Model)
tax_name = models.CharField(max_length = 250)
percentage = models.CharField(max_length = 250)
class Taxproduct(models.Model):
tax_name = ForeignKey(tax, on_delete = models.CASCADE)
percentage = models.CharField(max_length = 3)
class Product(models.Model):
product_name = models.CharField(max_length = 25)
description = models.CharField(max_length = 150)
category = models.ForeignKey(Category, on_delete = models.CASCADE)
sales = models.CharField(max_length = 25)
cost = models.CharField(max_length = 25)
tax_details = models.CharField(max_length = 250)
串行
class TaxSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Tax
fields = ('id','tax_name', 'tax_percentage')
class TaxproductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Taxproduct
fields = ('id', 'tax_name', 'percentage')
class ProductSerializer(serializers.HyperlinkedModelSerializer):
tax_details = TaxproductSerializer(many=True, read_only = True)
class Meta:
model = Product
fields = ('id', 'image','pro_name', 'description', 'sales', 'cost', 'tax_details')
所以請告訴我怎么做?
首先,您需要為模型添加一對多關系。 為此,您需要將ForeignKkey
字段添加到Taxproduct
模型:
class Taxproduct(models.Model)
tax_name = models.CharField(max_length=250)
percentage=models.CharField(max_length=250)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
這將添加到Product
模型屬性taxproduct_set
,它將返回相關稅的列表。 要將其添加到具有不同名稱的序列化程序(在您的情況下為tax_details
,請使用字段的source
參數:
class ProductSerializer(serializers.HyperlinkedModelSerializer):
tax_details = TaxproductSerializer(many=True,read_only=True, source='taxproduct_set')
class Meta:
model = Product
fields = ('id','pro_name','description','sales','cost','tax_details')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.