Malcolm Tredinnick wrote:
On Tue, 2006-06-27 at 23:53 -0400, bsdlogical wrote:
I've recently stumbled over a problem whose solution I can't find. I
have a class with two fields that use the built-in User class (from
django.contrib.auth.models) in a many-to-many relationship. However,
when I try to access or modify those fields, django throws an error
message. My class declaration is:
class Organization(models.Model):
name = models.CharField(maxlength=40)
sponsor = models.ManyToManyField(User,
related_name='sponsored_orgs', null=True)
members = models.ManyToManyField(User,
related_name='orgs_belonged_to', null=True)
test = models.ForeignKey(User)
The following code:
o = Organization()
o.sponsor
causes an error after the second line:
Traceback (most recent call last):
File "<console>", line 1, in ?
File
"/usr/local/lib/python2.4/site-packages/django/db/models/fields/related.py",
line 405, in __get__
target_col_name=qn(self.field.m2m_reverse_name())
File
"/usr/local/lib/python2.4/site-packages/django/db/models/fields/related.py",
line 244, in __init__
raise ValueError("%r instance needs to have a primary key value
before a many-to-many relationship can be used." % model)
ValueError: <class 'django.contrib.auth.models.User'> instance needs to
have a primary key value before a many-to-many relationship can be used.
When you create a many-to-many association, we store the pair of related
primary key values in the "join" table in the database. In order to
store that pair, both objects need to *have* a primary key. A new object
does not receive a primary key value until you save it (unless you
manually set the value yourself).
This will work:
o = Organization()
o.save()
o.sponser
Regards,
Malcolm
That definitely solved the problem. Thanks for the explanation!
Nick
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~----------~----~----~----~------~----~------~--~---
|