如何在单个请求中使用Djangorestframework serializers.save()方法创建多个模型对象

时间:2016-06-16 09:57:01

标签: django django-rest-framework

我想在单个请求上创建多个模型对象,每个模型对象都有自己唯一的ID

models.py

class DemoUserRequested(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(settings.AUTH_USER_MODEL,related_name="profile",verbose_name=("user"))
    name_of_obj =  models.CharField(max_length=254, blank=True)
    count_of_obj =  models.CharField(max_length=254, blank=True)
    Uuid =  models.CharField(max_length=254, blank=True,null=True)# i am generating the unique id

serializers.py

class UserProfileSerializer(serializers.ModelSerializer):
    # user = UserSerializer('user', read_only=True)

    class Meta:
        model = DemoUserRequested
        fields = ('id','name_of_obj','count_of_obj','Uuid')
        read_only_fields=('id','Uuid') # i'll generating the unique id 

    def __unicode__(self):
        return self.name_of_obj

views.py

def perform_create(self,serializer):
    serializer = serializer.UserProfileSerializer(data=self.request.data)
    if serializer.is_valid():
        # Cheking how meny objects user want create 
        count = serializer.validated_data.get('count_of_obj', 1)
        #if user choose to create 4 objcts I want run this loop crate 4 model objects
        #this example count = 4 
        for x in range(count):
            unic_id = uuid.uuid4()
            #I want create 4 objects 
            serializer.save(Uuid=unic_id)

但每次我运行此代码时,它都是我们的单一模型实例并更新4次,并最终创建一个对象。我怎么解决这个问题?  这可以在djangorestframework中做到吗?

1 个答案:

答案 0 :(得分:1)

我已经弄清楚了。这很容易做到。我已经通过这样做了

def perform_create(self, serializer):
    serializer = serializer.UserProfileSerializer(data=self.request.data)
    if serializer.is_valid():
        # Checking how many objects user want create 
        count = serializer.validated_data.get('count_of_obj', 1)
        #if user choose to create 4 objects I want run this loop crate 4 model objects
        #this example count = 4 
        for x in range(count):
            unic_id = uuid.uuid4()
            #I want create 4 objects 
            userobt = DemoUserRequested(
                name_of_obj=serializer.validated_data['name_of_obj'],
                Uuid = unic_id
            )
            userobt.save()

那么简单:)