【问题标题】:How to make a PUT/PATCH request with ListField field in Django-REST?如何在 Django-REST 中使用 ListField 字段发出 PUT/PATCH 请求?
【发布时间】:2020-07-16 13:49:09
【问题描述】:

我正在尝试为电影评论网站构建一个 rest-api。电影模型包含一个演员字段,它是一个列表字段,当使用 ModelViewSets 时,无法通过 HTML 发布 ListFields,所以我为所有列表字段设置了空白 = true,认为我将发出一个原始 PATCH 请求来更新空白字段,但我无法这样做。

models.py

class Movie(models.Model):
    movie_name = models.CharField(max_length = 100, unique = True)
    release_date = models.DateField(blank = True)
    description = models.TextField(max_length = 500)
    movie_poster = models.ImageField(blank = True)
    directors = ListCharField(
        base_field = models.CharField(max_length = 500),
        max_length = 6 * 500,
        blank = True
        )
    trailer_url = models.URLField()
    cast = ListCharField(
        base_field = models.CharField(max_length = 225),
        max_length = 11 * 225,
        blank = True
        )
    genre = ListCharField(
        base_field = models.CharField(max_length = 225),
        max_length = 11 * 255,
        blank = True
        )
    avg_rating = models.FloatField(validators = [MinValueValidator(0), MaxValueValidator(5)])
    country = models.CharField(max_length = 100)
    language = models.CharField(max_length = 100)
    budget = models.BigIntegerField(blank = True)
    revenue = models.BigIntegerField(blank = True)
    runtime = models.DurationField(blank = True)

序列化器

class MovieSerializer(ModelSerializer):
   cast = ListField(
       child = CharField(required = False), required = False,
       min_length = 0
   )
   genre = ListField(
       child = CharField(required = False), required = False,
       min_length = 0
   )

   directors = ListField(
           child = CharField(required = False), required = False,
           min_length = 0
       )
   class Meta:
       model = Movie
       fields = '__all__'

我使用 djano-mysql 来添加 ListCharField 字段类型。

【问题讨论】:

  • 很抱歉,由于某些 stackoverflow 政策,我无法添加屏幕快照,帖子中存在一些链接,可将您带到图片。

标签: django-rest-framework


【解决方案1】:

导致错误响应的原始放置请求

请求有一些尾随逗号,因此 API 需要更多值。

这是正确的请求内容 -

{
    "cast": [
        "aamir",
        "sakshi"
    ],
    "genre": [
        "biopic"
    ],
    "directors": [
        "nitesh tiwari"
    ]
}

【讨论】:

    猜你喜欢
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    相关资源
    最近更新 更多