【问题标题】:How to don't save null parameter in table if got parameter with null field in Django如果在Django中获得带有空字段的参数,如何不将空参数保存在表中
【发布时间】:2021-12-27 13:26:32
【问题描述】:

我有一些这样的参数表:

class Education(models.Model):
    title = models.CharField(default=None, max_length=100)
    content = models.TextField(default=None)

在来自客户端的 Django 请求中,content 字段可能等于 NULL。所以我想当 content 参数为 NULL 时,Django 不会将其保存在数据库中,但不会显示任何错误。 可能这个字段已经有数据,在 Update 请求客户端只想更改title 字段。

【问题讨论】:

    标签: django database orm model null


    【解决方案1】:

    在您的表单/序列化程序中将content 字段设置为不需要,因此如果客户端不想更新该字段,它根本不会传递值。

    from django.forms import ModelForm
    from .models import Education
    
    
    class EducationForm(ModelForm):
       class Meta:
          model = Education
          fields = ('title', 'content')
    
       def __init__(self, *args, **kwargs):
          super().__init__(*args, **kwargs)
          self.fields['content'].required = False
    

    【讨论】:

      【解决方案2】:

      我找到了,就像这样:

      class EducationSerializer(serializers.ModelSerializer):
          class Meta:
              model = Education
              fields = ['title', 'content')
              extra_kwargs = {'content': {'required': False}} 
      

      【讨论】:

      • 不行,需要设置:extra_kwargs = {'content': {'required': False}}
      • @RedWheelbarrow 谢谢你修复它。
      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-08
      • 2019-07-16
      • 2023-01-22
      相关资源
      最近更新 更多