如何在django restframework中创建必填字段

qlvxas9a  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(138)

我构建了一个博客API,Post模型是:问题是当我想创建一个没有正文内容的帖子时,错误是

class Post(models.Model):

    STATUS_CHOICES = [
        ('P', _('Published')),
        ('D', _('Draft')),
        ('R', _('reject'))
    ]
    title = models.CharField(verbose_name=_("title"), max_length=255)
    slug = models.SlugField(null=True, unique=True, allow_unicode=True)
    lead = models.CharField(verbose_name=_(
        "lead"), max_length=1024, blank=True, null=True)
    body = models.TextField(verbose_name=_("context"))
    thumbnail = models.ImageField(verbose_name=_(
        "thumbnail"), upload_to='posts', blank=True, null=True)
    author = models.ForeignKey(UserAccount, verbose_name=_(
        "author"), on_delete=models.CASCADE)
    status = models.CharField(
        _("status"), max_length=1, choices=STATUS_CHOICES, default=STATUS_CHOICES[1][0])
    publish_time = models.DateTimeField(
        verbose_name=_("published at"), default=timezone.now)

    created_at = models.DateTimeField(
        verbose_name=_("created at"), auto_now_add=True)
    updated_at = models.DateTimeField(
        verbose_name=_("updated at"), auto_now=True)

    category = models.ManyToManyField(
        Category, verbose_name=_("Categorys"), related_name='Categorys')
    like_count = models.IntegerField(verbose_name=_("like"), default=0)
    dislike_count = models.IntegerField(verbose_name=_("dislike"), default=0)
    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

    class Meta:
        ordering = ['-publish_time']

    def __str__(self):
        return self.title
class PostListSerializer(ModelSerializer):
    dietale_url = HyperlinkedIdentityField(
        view_name='api:Post_detail'
    )
    author = SerializerMethodField()

    class Meta:
        model = Post
        fields = [
            'title',
            'author',
            'lead',
            'dietale_url',
        ]

    def get_author(self, obj):
        return obj.author.name

问题是,当我想创建一个职位,它返回错误:

{
    "title": [
        "This field is required."
    ]
}
    • 需要更多字段,如作者正文和...**
    • 为什么只有标题是必填字段,其他字段会发生什么情况**
bvjxkvbb

bvjxkvbb1#

你的title在你的django模型中不能是blank或者null,并且你使用的序列化器是ModelSerializer,所以它将自动被需要。
如果您不希望您的字段是必需的(或者在序列化程序中覆盖您的字段),则需要删除blank = Truenull = True
文件:
如果您使用的是Model Serializer,并且在Model中的字段中指定了blank = True或default或null = True,则默认值将为False。

相关问题