如何使用objects.create保存django字段



我有一个模型:

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')

我想保存位置字段给primary-key。

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.

请帮助如何保存位置字段到数据库

gen_certi变量是一个查询集(对象列表),因为您正在使用filter() -使用get()代替:

gen_certi = Certificate.objects.get(pk = kwargs.get('cert_id')).generic_certificate
事实上,我不明白你打算在这个视图中做什么。如果您正在修改对象,则不需要覆盖现有字段,只需更新request.POST中传递给视图的字段,例如position:
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()
    ...

希望对你有帮助。

相关内容

  • 没有找到相关文章

最新更新