Django

Code

Ticket #4214 (closed: fixed)

Opened 1 year ago

Last modified 1 year ago

Document how to update a foreign key in db-api

Reported by: david@kazserve.org Assigned to: jacob
Milestone: Component: Documentation
Version: SVN Keywords:
Cc: Triage Stage: Accepted
Has patch: 1 Needs documentation: 0
Needs tests: 0 Patch needs improvement: 0

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

db-api.patch (0.7 kB) - added by david@kazserve.org on 05/04/07 02:58:03.
patch that explains how to update a foreign key field

Change History

05/04/07 01:19:25 changed by ubernostrum

  • needs_better_patch changed.
  • needs_tests changed.
  • needs_docs changed.

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.

05/04/07 02:58:03 changed by david@kazserve.org

  • attachment db-api.patch added.

patch that explains how to update a foreign key field

05/16/07 21:01:45 changed by Simon G. <dev@simon.net.nz>

  • has_patch set to 1.
  • summary changed from API inconsistency not noted in documentation to Document how to update a foreign key in db-api.
  • 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.

06/07/07 13:24:28 changed by jacob

  • status changed from new to closed.
  • resolution set to fixed.

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


Add/Change #4214 (Document how to update a foreign key in db-api)




Change Properties
Action