Opened 13 years ago

Closed 13 years ago

#4214 closed (fixed)

Document how to update a foreign key in db-api

Reported by: david@… Owned by: Jacob
Component: Documentation Version: master
Severity: Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I am not sure of best place to highlight this in the documentation, but it cost me an hour to find out the hard way :)

API reference to foreignkey fields appears to require appending _id to fieldname.

class Nlgroup(models.Model):
  o1object = models.ForeignKey('People', related_name='nlgroupo1object', null=True, blank=True, editable=False)
  givens = models.CharField(maxlength=25, verbose_name="Givens", blank= True, editable=False)
  def save(self): 
    if not
      p = People.objects.create(orgname=self.description)
# self.o1object is not saved into the o1object field
      self.o1object_id = 
    super(Nlgroup, self).save() 

Attachments (1)

db-api.patch (749 bytes) - added by david@… 13 years ago.
patch that explains how to update a foreign key field

Download all attachments as: .zip

Change History (4)

comment:1 Changed 13 years ago by James Bennett

If you want to assign the primary-key value of the related object, yes; in general, though, the field itself will accept an object of the correct type to be assigned to the relation. For example, this would work:

self.o1object = p

Given that it's far more common (and preferable) to assign the object to the field rather than do indirection on assigning a primary key value to the correct attribute, I'm not sure this is worth doing much about.

Changed 13 years ago by david@…

Attachment: db-api.patch added

patch that explains how to update a foreign key field

comment:2 Changed 13 years ago by Simon G. <dev@…>

Has patch: set
Summary: API inconsistency not noted in documentationDocument how to update a foreign key in db-api
Triage Stage: UnreviewedAccepted

I think a few people have had problems with this before, so it may be worth adding the above example to the docs.

comment:3 Changed 13 years ago by Jacob

Resolution: fixed
Status: newclosed

(In [5437]) Fixed #4214: added a bit of explicit info on updating FK fields to db-api.txt. Thanks, david@….

Note: See TracTickets for help on using tickets.
Back to Top