Opened 8 years ago

Closed 8 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: UI/UX:


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@… 8 years ago.
patch that explains how to update a foreign key field

Download all attachments as: .zip

Change History (4)

comment:1 Changed 8 years ago by ubernostrum

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

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 8 years ago by david@…

patch that explains how to update a foreign key field

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

  • Has patch set
  • Summary changed from API inconsistency not noted in documentation to Document how to update a foreign key in db-api
  • Triage Stage changed from Unreviewed to Accepted

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 8 years ago by jacob

  • Resolution set to fixed
  • Status changed from new to closed

(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