Django休息框架:如何在泛型API类中自动设置Creation的值?

lzfw57am  于 2023-03-20  发布在  Go
关注(0)|答案(1)|浏览(102)

我想让我的API在创建过程中自动将用户值分配给登录用户,但我不知道如何分配。
型号:

class Template(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='templates')
    name = models.CharField(max_length=200)
    base_attribute_points = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(10000)])
    base_skill_points = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(10000)])
    base_advantage_points = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(10000)])
    min_attribute_value = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(100)])
    max_attribute_value = models.IntegerField(
        validators=[MinValueValidator(0), MaxValueValidator(1000)])
    replace_attributes_derived_values = models.BooleanField()
    replace_attributes_skills = models.BooleanField()

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
    
    def __str__(self):
        return f'{self.user}: {self.name}'

串行器:

class TemplateSerializer(serializers.ModelSerializer):
    characteristics = CharacteristicSerializer(many=True, read_only=False)
    attributes = AttributeSerializer(many=True, read_only=False)
    skill_categories = SkillCategorySerializer(many=True, read_only=False)
    derived_values = DerivedValueSerializer(many=True, read_only=False)
    levels = LevelSerializer(many=True, read_only=False)
    class Meta:
        model = Template
        fields = ['id', 'user', 'name', 'base_attribute_points', 'base_skill_points', 'base_advantage_points', 'min_attribute_value', 'max_attribute_value',
                  'replace_attributes_derived_values', 'replace_attributes_skills', 'characteristics', 'attributes', 'skill_categories', 'derived_values', 'levels']

查看:

class TemplateList(generics.ListCreateAPIView):
    serializer_class = TemplateSerializer
    queryset = Template.objects.all()
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user  = self.request.user
        return user.templates.all()
    
    #def perform_create(self, serializer):
    #    print(serializer.validated_data)
    #    serializer.save()

就像我说的,我想把用户设置为登录的用户。另外,如果用户字段不是必需的,那就太好了。我已经尝试了很多方法,但我得到的都是错误。我试图配置perform_create方法来改变那里的值,但没有任何效果。
这方面的最佳做法是什么?

bnl4lu3b

bnl4lu3b1#

从请求对象获取用户对象

class TemplateList(generics.ListCreateAPIView):
serializer_class = TemplateSerializer
queryset = Template.objects.all()
permission_classes = [permissions.IsAuthenticated]

def get_queryset(self):
    user  = self.request.user
    return user.templates.all()

def perform_create(self, serializer):
    serializer.save(user=self.request.user)

相关问题