我选择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模型中存储数组?
答案 0 :(得分:1)
get_or_create()
方法返回一个(object,created)元组,其中object是创建的对象,并且创建的是一个布尔值,指定是否创建了新对象。
detail_instance, created = PostDetail.objects.get_or_create(post=post_instance)