如果在 Django 中得到带有空字段的参数,如何不在 table 中保存空参数
How to don't save null parameter in table if got parameter with null field in Django
我 table 有一些像这样的参数:
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
字段。
在您的表单/序列化程序中将 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
我找到了,就像这样:
class EducationSerializer(serializers.ModelSerializer):
class Meta:
model = Education
fields = ['title', 'content')
extra_kwargs = {'content': {'required': False}}
我 table 有一些像这样的参数:
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
字段。
在您的表单/序列化程序中将 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
我找到了,就像这样:
class EducationSerializer(serializers.ModelSerializer):
class Meta:
model = Education
fields = ['title', 'content')
extra_kwargs = {'content': {'required': False}}