質問

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top