Django-perform_create()始终创建2个实例

时间:2019-06-10 16:57:03

标签: python django database

我有以下model.py文件:

class CustomUser(AbstractUser):
    created = models.DateTimeField(auto_now_add=True)
    job = models.CharField(max_length=100, blank=True)
    photo =  models.FileField(upload_to='Images/',
                                     default='Images/None/No-img.jpg')

    def __str__(self):
        return "%s%s" % (self.first_name, self.last_name)

    class Meta:
        ordering = ('created', )

class Clique(models.Model):

    # holds when the clique was created
    created = models.DateTimeField(auto_now_add=True)

    # holds the name of the clique
    name = models.CharField(max_length=100, blank=False)

    # holds the members of the clique
    members = models.ManyToManyField(CustomUser, blank=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('created', )

基本上,我有一个用户模型和一个集团模型。 一个用户可以处于多个团体中,一个团体可以具有多个用户。 我想要的是,当用户创建集团时,应该将他作为成员自动添加到集团中。 因此,在我的views.py文件中,我像这样重写perform_create()方法:

class CreateClique(generics.CreateAPIView):
    '''
        This class creates a Clique for the user who made the
        request.
    '''

    # define the serializer class 
    serializer_class = CliqueSerializer

    # we use token authentication
    authentication_classes = (TokenAuthentication,)

    # user must be authenticated
    permission_classes = (permissions.IsAuthenticated,)

    def perform_create(self, serializer):
        user = self.request.user    # get the user
        data = self.request.data    # get the data the user has sent

        # first check if we have the name of the clique
        if 'name' in data:
            name = data['name'] # retrieve the clique name

            clique = Clique.objects.create(name=name)
            clique.members.add(user)


        serializer.save()  

但是当我创建一个集团(例如名称为“ Test”)时,我的数据库中就有2个该集团的实例。我可以通过shell命令看到这一点:

>>> from users.models import Clique
>>> cl = Clique.objects.all()
>>> cl
<QuerySet [<Clique: Test>, <Clique: Test>]>
>>> 

为什么会这样?我该如何解决呢?

1 个答案:

答案 0 :(得分:2)

之所以会这样,是因为您有Clique.objects.create(name=name)serializer.save(),这就是为什么会有两个实例的原因。

基本上你需要做的是

def perform_create(self, serializer):
    serializer.save()  # here your object will be created and put in serializer.instance
    serializer.instance.members.add(self.request.user)