Question

My models:

class ActsInformationModel(models.Model):
    name=models.CharField(max_length=50, unique=True)
    prelexRespProposId1=models.ForeignKey('RespProposModel', related_name='prelexRespProposId1', blank=True, null=True, default=None)

class RespProposModel(models.Model):
    respPropos=models.CharField(max_length=50, unique=True)

My view:

...
dataDic["prelexRespProposId1"]=RespProposModel.objects.get(respPropos=respPropos)
print dataDic["prelexRespProposId1"].id #display 1 -> OK
dataDic["name"]="test"
act=ActsInformationModel.objects.get(...)
act.__dict__.update(dataDic)
print act.name #displays test
print "act.prelexRespProposId1", act.prelexRespProposId1 #display None -> PB
act.prelexRespProposId1=RespProposModel.objects.get(id=dataDic["prelexRespProposId1"].id)
print "act.prelexRespProposId1.id", act.prelexRespProposId1 #display 1 -> OK

Why do I have to do another query to get the value of the field ? Other question, maybe related: why do I have to use the object to fill the foreign key field and not just an integer?

Was it helpful?

Solution

Solved!

When creating a foreign key, django saves the field with the original name + "_id". So my field "prelexRespProposId1" was in fact named "prelexRespProposId1_id". I had to use the latter name to have my code working!

My models:

class ActsInformationModel(models.Model):
    prelexRespProposId1=models.ForeignKey('RespProposModel', related_name='prelexRespProposId1', blank=True, null=True, default=None)

My view:

...
dataDic["prelexRespProposId1_id"]=RespProposModel.objects.get(respPropos=respPropos)
print dataDic["prelexRespProposId1_id"].id #display 1 -> OK
act=ActsInformationModel.objects.get(...)
act.__dict__.update(dataDic)
print "act.prelexRespProposId1_id", act.prelexRespProposId1_id #display 1 -> Solved!!!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top