我有一个模特:
class Certificate(models.Model):
comments = models.TextField(blank=True, default='')
generic_certificate = models.ForeignKey(GenericCertificate, related_name='certificates_awarded')
tag = models.ForeignKey('Tag', related_name='certificates_awarded', null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
history_timestamp = models.DateTimeField(auto_now=True)
rewardee = models.ForeignKey(OrganisationUser, related_name='certificates_rewarded')
position = models.CharField(max_length=50, default = '0,0')
我想保存给定主键的位置字段。
这是views.py:
def post(self, request , *args , **kwargs):
comments = Certificate.objects.values("comments").filter(pk = kwargs.get('cert_id') )
gen_certi = Certificate.objects.values("generic_certificate").filter(pk = kwargs.get('cert_id') )
tag = Certificate.objects.values("tag").filter(pk = kwargs.get('cert_id') )
history_timestamp = Certificate.objects.values("history_timestamp").filter(pk = kwargs.get('cert_id') )
rewardee = Certificate.objects.values("rewardee").filter(pk = kwargs.get('cert_id') )
position = request.POST.get('hid')
position = str([position])
a = Certificate.objects.create( comments=comments, generic_certificate = gen_certi , tag=tag,rewardee=rewardee, position=position )
print a
给出错误:
Exception Value:
Cannot assign "[{'generic_certificate': 2}]": "Certificate.generic_certificate" must be a "GenericCertificate" instance.
请帮助如何将位置字段保存到数据库中。
答案 0 :(得分:3)
gen_certi
变量是一个查询集(对象列表),因为您使用的是filter()
- 请改为使用get()
:
gen_certi = Certificate.objects.get(pk = kwargs.get('cert_id')).generic_certificate
实际上,我不明白你打算在视图中做什么。如果要修改对象,则无需覆盖现有字段,只需更新传递给request.POST
中视图的字段,如位置:
try:
certificate = Certificate.objects.get(pk = kwargs.get('cert_id'))
certificate.position = request.POST.get('hid')
certificate.save()
except DoesNotExist:
# create new certificate
certificate = Certificate()
...
希望有所帮助。