python Django休息时间:忽略不属于模型的自定义字段

zc0qhyus  于 2022-12-17  发布在  Python
关注(0)|答案(3)|浏览(109)

我的TimeReport模型如下所示:

class TimeReport(models.Model):
    minutes_spent = models.PositiveIntegerField()
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)
    reported_for = models.DateField()
    note = models.TextField(null = True, blank=True)
    status = models.CharField(max_length=50, choices=State.choices, default=State.new)
    user = models.ForeignKey(User, on_delete=models.PROTECT)

我的模型序列化器:

class TimeReportCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = TimeReport
        fields = (
            'id',
            'minutes_spent',
            'reported_for', 
            'note',
            'status',
            'task_custom_id',
            )
    
    task_custom_id = serializers.CharField()

    def create(self, validated_data):
        user = User.objects.get(auth_user_id = self.context['user_id'])
        task = Task.objects.filter(custom_id = validated_data['task_custom_id']).filter(user = user.id).first()
        
        report = TimeReport(**validated_data)
        report.user = user
        report.task = task
        report.save()
        return report

因此,问题是,我想在序列化器中获取一个自定义值,它不是模型的一部分,并使用它执行一些自定义逻辑-在本例中,在数据库中搜索正确的'task'。但当我尝试使用report = TimeReport(**validated_data)解析模型时,它给了我一个异常:

TypeError at /api/report/
TimeReport() got an unexpected keyword argument 'task_custom_id'

我对Django和python本身还不太熟悉,那么-什么是最好的方法呢?

qjp7pelc

qjp7pelc1#

如果您只打算将该字段用于创建,则应使用write_only选项。

task_custom_id = serializers.CharField(write_only=True)

请在www.example.com查看文档https://www.django-rest-framework.org/api-guide/fields/#write_only

k0pti3hp

k0pti3hp2#

您只需从字典中删除task_custom_id

class TimeReportCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = TimeReport
        fields = (
            'id',
            'minutes_spent',
            'reported_for', 
            'note',
            'status',
            'task_custom_id',
            )
    
    task_custom_id = serializers.CharField()

    def create(self, validated_data):
        user = User.objects.get(auth_user_id = self.context['user_id'])
        task_custom_id = validated_data.pop("task_custom_id")
        task = Task.objects.filter(custom_id = task_custom_id).filter(user = user.id).first()
        report = TimeReport(**validated_data)
        report.user = user
        report.task = task
        report.save()
        return report
hfwmuf9z

hfwmuf9z3#

task = Task.objects.filter(custom_id = validated_data.pop('task_custom_id')).filter(user = user.id).first()

validated_data将返回(task_custom_id=value,field1=value1 ...),task_custom_id不是TimeReport字段,因此您所需要的只是在调用构造函数TimeReport之前从validated_data中弹出**它

相关问题