Opened 18 years ago

Closed 18 years ago

#4214 closed (fixed)

Document how to update a foreign key in db-api

Reported by: david@… Owned by: Jacob
Component: Documentation Version: dev
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

Description

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 self.id:
      p = People.objects.create(orgname=self.description)
# self.o1object is not saved into the o1object field
      self.o1object_id = p.id 
    super(Nlgroup, self).save() 

Attachments (1)

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

Download all attachments as: .zip

Change History (4)

comment:1 by James Bennett, 18 years ago

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.

by david@…, 18 years ago

Attachment: db-api.patch added

patch that explains how to update a foreign key field

comment:2 by Simon G. <dev@…>, 18 years ago

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 by Jacob, 18 years ago

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