如何将数据放入CharField(validators = [validate_comma_separated_integer_list])?

时间:2017-11-25 13:13:12

标签: django django-models django-forms django-rest-framework django-views

我选择CharField(validators = ...)替代CommaSeparatedInteger字段以将数组存储到字段中。

Http请求包含selectedColorsIds正文字段,我想将数据放入color模型的PostDetail字段

...
"selectedColorIds": Array [
    112,
    110,
  ],
...

models.py

from django.core.validators import validate_comma_separated_integer_list

class PostDetail(models.Model):
    ...
    color = models.CharField(validators=[validate_comma_separated_integer_list], max_length=30, blank=True, null=True)
    ...

views.py:>但是当我尝试将数组放入字段时,我收到此错误。 AttributeError: 'tuple' object has no attribute 'color' error

color = self.request.data.get('selectedColorIds') # [112, 110]
detail_instance = PostDetail.objects.get_or_create(post=post_instance)
detail_instance.color = color  <<- error here

为什么我会收到此错误,如何在Django模型中存储数组?

1 个答案:

答案 0 :(得分:1)

get_or_create() 方法返回一个(object,created)元组,其中object是创建的对象,并且创建的是一个布尔值,指定是否创建了新对象。

detail_instance, created = PostDetail.objects.get_or_create(post=post_instance)