Django Restful_Api一次发布Json多个记录

时间:2017-07-10 13:34:43

标签: python json django

我使用Django Restful Api,我想在一段时间内发布记录(多个记录!),模型,序列化,视图集如下

有人有什么建议吗?谢谢你的推荐!

模型

class Brand(models.Model):
    Company_Group = models.ManyToManyField(Company)
    Brand_Group = models.CharField(u'Brand Group',max_length=255, default="")
    Pref_Brand_Name_Flg = models.CharField(u'Preferred Brand Name Flag',max_length=255, default="")
    Pref_Brand_Name = models.CharField(u'Preferred Brand Name',max_length=255, default="")
    PrimaryContact = models.ForeignKey(UserRole, null=True, blank=True) #primarybroker
    Protect_period = models.CharField(u'Protect period',max_length=255, default="")
    # Pref_Brand_Name = models.CharField(u'Preferred Brand Name',max_length=255, default="")
    Brand_Name = models.CharField(u'Brand Name',max_length=255, default="")
    Brand_Name_SC = models.CharField(u'Brand Name in Local Language',max_length=255, default="")
    Year_Enter_Market = models.CharField(u'Entered Market in (Year)',max_length=255, default="")
    Category_Display = models.CharField(u'Category Display',max_length=255, default="")
    Category_1_Code = models.CharField(u'Category',max_length=255, default="")
    Category_2_Code = models.CharField(u'Sub Category',max_length=255, default="")
    Price_Low = models.CharField(u'Price Range - Low',max_length=255, default="")
    Price_High = models.CharField(u'Price Range - High',max_length=255, default="")
    Size_Low = models.CharField(u'Typical Store Size - Low',max_length=255, default="")
    Size_High = models.CharField(u'Typical Store Size - High',max_length=255, default="")
    Headerquater = models.CharField(u'Headerquater',max_length=255, default="")
    Status = models.CharField(u'Status',max_length=255, default="")
    Created_On = models.DateField(u'Created On',auto_now_add=True)
    Created_By = models.CharField(u'Created By',max_length=255, default="")
    Modified_On = models.DateField(u'Modified On', auto_now=True)
    Modified_By = models.CharField(u'Modified By',max_length=255, default="")
    Agreement_InPlace_Flg = models.CharField(u'TR Agreement in place?',max_length=20, default="")
    Web_Site = models.CharField(u'Web Site',max_length=20, default="")
    Comment = models.CharField(u'Comment',max_length=20, default="")

viewset

class BrandViewSet(viewsets.ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSerializer

串行

class BrandSerializer(serializers.HyperlinkedModelSerializer):
    PrimaryContact_id = serializers.ReadOnlyField(source='PrimaryContact.id', read_only=True)
    def __init__(self, *args, **kwargs):
        many = kwargs.pop('many', True)
        super(BrandSerializer, self).__init__(many=many, *args, **kwargs)

    class Meta:
        model = Brand
        fields = data_export_setting.Brand_form_stand # +options ??
        #Brand_detail = serializers

“myTest code”:a.py

item = [{"id":"2","PrimaryContact_id":"00000","Pref_Brand_Name_Flg":"00000","Protect_period":"test_for_Protect_period_1","Pref_Brand_Name":"Test","Brand_Name":"Chanel Group","Brand_Name_SC":"test","Year_Enter_Market":"test","Category_Display":"test","Category_1_Code":"api","Category_2_Code":"api","Price_Low":"test","Price_High":"test","Size_High":"test","Headerquater":"test","Status":"test","Created_On":"2017-06-14","Modified_By":"2017-07-08","Modified_On":"000"},{"id":"3","PrimaryContact_id":"1111","Pref_Brand_Name_Flg":"11111","Protect_period":"ppppp","Pref_Brand_Name":"Test","Brand_Name":"Chanel Group 2","Brand_Name_SC":"test","Year_Enter_Market":"test","Category_Display":"test","Category_1_Code":"api","Category_2_Code":"api","Price_Low":"test","Price_High":"test","Size_High":"test","Headerquater":"test","Status":"test","Created_On":"2017-06-14","Modified_By":"2017-07-08","Modified_On":"000"}]

data=json.dumps(item)                                                     
def test_get_user_list_3():
    resp = requests.post(urlname,auth=AUTH,data=data,headers={ "Content-Type":"application/json","Accept": "application/json"})    
test_get_user_list_3()

如果项目是一条记录,则可以

item ={"id":"1","PrimaryContact_id":"00000","Pref_Brand_Name_Flg":"00000","Protect_period":"test_for_Protect_period_1","Pref_Brand_Name":"Test","Brand_Name":"Chanel Group","Brand_Name_SC":"test","Year_Enter_Market":"test","Category_Display":"test","Category_1_Code":"api","Category_2_Code":"api","Price_Low":"test","Price_High":"test","Size_High":"test",Headerquater":"test","Status":"test","Created_On":"2017-06-14","Modified_By":"2017-07-08","Modified_On":"000"},

2 个答案:

答案 0 :(得分:0)

DRF documentation所示,您可以使用ListSerializer创建模型的多个实例。

最好的办法是使用您自己的自定义ListSerializer方法创建单独的序列化程序(.create()),以创建模型的多个实例。然后在您的视图中,您编写一些业务逻辑来检查它是单个对象还是多个对象的列表,并将它们发送到适当的序列化程序以进行创建。请务必查看ListSerializer以及如何使用many=True

您可以使用自己的自定义.create()方法使用相同的序列化程序,并在其中包含业务逻辑,但请查看文档并查看创建多个对象实例的推荐方法。

答案 1 :(得分:0)

好的,我花了相当多的时间来尝试这项工作。下面是我用来制作批量创建的代码。

get_serializer默认使用的ModelViewSet方法在没有many=True的数据中传递,因此您必须覆盖它并确保检查列表而不是字典的请求

这是能够从列表中批量创建项目所需的唯一更改。

models.py

class Brand(models.Model):
    # ------------------------------------------
    # Relations
    # ------------------------------------------
    Company_Group = models.ManyToManyField(Company)
    PrimaryContact = models.ForeignKey(User, null=True, blank=True)

    # ------------------------------------------
    # Attributes
    # ------------------------------------------

    # Brand attrs
    Brand_Name = models.CharField(u'Brand Name',max_length=255, blank=True)
    Brand_Group = models.CharField(u'Brand Group',max_length=255, blank=True)
    Pref_Brand_Name = models.CharField(u'Preferred Brand Name',max_length=255, blank=True)
    Brand_Name_SC = models.CharField(u'Brand Name in Local Language',max_length=255, blank=True)
    Pref_Brand_Name_Flg = models.CharField(u'Preferred Brand Name Flag',max_length=255, blank=True)

    # Record management attrs
    Modified_On = models.DateField(u'Modified On', auto_now=True)
    Created_On = models.DateField(u'Created On', auto_now_add=True)
    Created_By = models.CharField(u'Created By', max_length=255, blank=True)
    Modified_By = models.CharField(u'Modified By', max_length=255, blank=True)

    # Category attrs
    Category_1_Code = models.CharField(u'Category', max_length=255, blank=True)
    Category_2_Code = models.CharField(u'Sub Category', max_length=255, blank=True)
    Category_Display = models.CharField(u'Category Display',max_length=255, blank=True)

    # Pricing attrs
    Price_Low = models.CharField(u'Price Range - Low', max_length=255, blank=True)
    Price_High = models.CharField(u'Price Range - High', max_length=255, blank=True)

    # Store attrs
    Size_Low = models.CharField(u'Typical Store Size - Low', max_length=255, blank=True)
    Size_High = models.CharField(u'Typical Store Size - High', max_length=255, blank=True)

    # Company attrs
    Status = models.CharField(u'Status', max_length=255, blank=True)
    Comment = models.CharField(u'Comment', max_length=20, blank=True)
    Web_Site = models.CharField(u'Web Site', max_length=20, blank=True)
    Headerquater = models.CharField(u'Headerquater', max_length=255, blank=True)
    Protect_period = models.CharField(u'Protect period', max_length=255, blank=True)
    Year_Enter_Market = models.CharField(u'Entered Market in (Year)', max_length=255, blank=True)
    Agreement_InPlace_Flg = models.CharField(u'TR Agreement in place?', max_length=20, blank=True)

    def __str__(self):
        return self.Brand_Name

    class Meta:
        db_table = 'brand'

serializers.py

class BrandSerializer(serializers.ModelSerializer):

    class Meta:
        model = Brand
        fields = '__all__'

views.py

class BrandViewSet(viewsets.ModelViewSet):
    model = Brand
    serializer_class = BrandSerializer
    queryset = Brand.objects.all()

    def get_serializer(self, *args, **kwargs):
        if 'data' in kwargs:
            data = kwargs['data']

            if isinstance(data, list):
                kwargs['many'] = True

        return super().get_serializer(*args, **kwargs)

urls.py

from rest_framework.routers import DefaultRouter

from .views import BrandViewSet

router = DefaultRouter()
router.register(r'brand', BrandViewSet)

urlpatterns = router.urls

我使用postman以这种格式发送数据(JSON):

[  
   {  
      "Brand_Name":"",
      "Brand_Group":"",
      "Pref_Brand_Name":"",
      "Brand_Name_SC":"",
      "Pref_Brand_Name_Flg":"",
      "Created_By":"",
      "Modified_By":"",
      "Category_1_Code":"",
      "Category_2_Code":"",
      "Category_Display":"",
      "Price_Low":"",
      "Price_High":"",
      "Size_Low":"",
      "Size_High":"",
      "Status":"",
      "Comment":"",
      "Web_Site":"",
      "Headerquater":"",
      "Protect_period":"",
      "Year_Enter_Market":"",
      "Agreement_InPlace_Flg":"",
      "PrimaryContact":null,
      "Company_Group":[  
         1
      ]
   },
   {  
      "Brand_Name":"",
      "Brand_Group":"",
      "Pref_Brand_Name":"",
      "Brand_Name_SC":"",
      "Pref_Brand_Name_Flg":"",
      "Created_By":"",
      "Modified_By":"",
      "Category_1_Code":"",
      "Category_2_Code":"",
      "Category_Display":"",
      "Price_Low":"",
      "Price_High":"",
      "Size_Low":"",
      "Size_High":"",
      "Status":"",
      "Comment":"",
      "Web_Site":"",
      "Headerquater":"",
      "Protect_period":"",
      "Year_Enter_Market":"",
      "Agreement_InPlace_Flg":"",
      "PrimaryContact":null,
      "Company_Group":[  
         1
      ]
   }
]