出现以下错误无法分配"u'167 '":"部门.组织"必须是"组织"示例。
我已尝试各种方法发送组织ID,但均未成功:
Request Method: POST
Request URL: http://127.0.0.1:8081/profiles/api/createorganisation/
Django Version: 1.8.14
Exception Type: ValueError
Exception Value:
Cannot assign "u'167'": "Department.organization" must be a "Organization" instance.
Exception Location: /usr/local/lib/python2.7/site-packages/django/db/models/fields/related.py in __set__, line 639
这是模型
class Department(models.Model):
"""
Make department codes selectable and stuff
"""
organization = models.ForeignKey(Organization, related_name="departments")
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, editable=False)
users = models.ManyToManyField("CustomUser", related_name="departments", blank=True)
enter code here
序列化程序类
class DepartmentCreateSerializer(serializers.ModelSerializer):
organization = serializers.CharField()
name = serializers.CharField()
slug = serializers.CharField()
class Meta:
model = Department
fields = ('pk','organization','name','slug')
这是我的密码
org = Organization.objects.get(slug="tata5").id
department = {
"organization":org,
"name" : "finance1",
"slug" : "finance1" ,
}
logging.warning(department)
instance = DepartmentCreateSerializer(data=department)
instance.organization = org
instance.is_valid(raise_exception=True)
instance.save()
# createDepartment.is_valid()
# createDepartment.save()
return Response(instance, status=status.HTTP_200_OK)
1条答案
按热度按时间vhmi4jdf1#
您正在使用
serializers.CharField()
,因此它尝试设置department.organization = 'id'
,而不是将其设置为实际的Organization
示例,您应该使用serializers.PrimaryKeyRelatedField
,然后将ID输入序列化为Organization
示例。