简体   繁体   中英

How to save django fields using objects.create?

I have a model :

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

I want to save position fields given primary-key.

Here is 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

Its giving error :

Exception Value:    
Cannot assign "[{'generic_certificate': 2}]": "Certificate.generic_certificate" must be a "GenericCertificate" instance.

Please help how to save position field into database.

gen_certi variable is a queryset (list of objects), because you are using filter() - use get() instead:

gen_certi = Certificate.objects.get(pk = kwargs.get('cert_id')).generic_certificate

Actually, I don't understand what are you planning to do in the view. If you are modifying the object, there is no need to overwrite the existing fields, just update the fields that are passed to the view in request.POST , like 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()
    ...

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM