Django many-to-many model DRF

前端 未结 5 1508
执念已碎
执念已碎 2021-01-26 04:37

I have the following model structure:

class Project(models.Model):
  author = models.ManyToManyField(Account)
  name = models.CharField(max_length=40, default=\'         


        
5条回答
  •  醉话见心
    2021-01-26 05:10

    Please check...

    your model.py

    class Account(AbstractBaseUser):
      email = models.EmailField(unique=True)
      username = models.CharField(max_length=40, unique=True)
      first_name = models.CharField(max_length=40, blank=True)
      last_name = models.CharField(max_length=40, blank=True)
      tagline = models.CharField(max_length=140, blank=True)
      is_admin = models.BooleanField(default=False)
      created_at = models.DateTimeField(auto_now_add=True)
      updated_at = models.DateTimeField(auto_now=True)
      objects = AccountManager()
      USERNAME_FIELD = 'email'
      REQUIRED_FIELDS = ['username']
    
    
    class Project(models.Model):
          author = models.ManyToManyField(Account)
          name = models.CharField(max_length=40, default='NewBook')
    

    your serializer.py

    class ProjectSerializer(serializers.ModelSerializer):
        author = AccountSerializer(read_only=True, required=False)
    
        class Meta:
            model = Project
            fields = ('id', 'author', 'name')
            read_only_fields = ('id')
    
        def get_validation_exclusions(self, *args, **kwargs):
            exclusions = super(ProjectSerializer, self).get_validation_exclusions()
            return exclusions + ['author']
    

    and finally your view.py is

    class ProjectViewSet(viewsets.ModelViewSet):
      queryset = Project.objects.order_by('-name')
      serializer_class = ProjectSerializer
    
      def perform_create(self, serializer):
        instance = serializer.save(author=self.request.user)
        return super(ProjectViewSet, self).perform_create(serializer)
    

提交回复
热议问题