On 10/15/06, Malcolm Tredinnick <[EMAIL PROTECTED]> wrote: > The value of Users.icon either has to be a valid primary key value in > the table for the Icon model or NULL (of you have null=True in the > ForeignKey constructor). This is because a Django ForeignKey field is a > true foreign key in the sense that it creates a field containing the > primary key of the foreign table *and* it creates a constraint ensuring > that the values in that field are valid (i.e. values from the > corresponding field in the foreign table). The constraint is significant > here. So putting a non-existent non-NULL value in that field means it is > no longer a foreign key.
Yes, I think that in my legacy database the relationship is not implemented on the database level (with constraints (?)) but only on the php, aplication level. Likewise, that "user.icon = -1" means "default icon for this user" is also only implemented in php, and the default icon does not even exist in the database. > If you want to use Django's foreign key functionality, you will need to > make sure this field really is a foreign key (including satisfying the > constraint). Moberly's suggestion of creating a dummy record with > primary key value of -1 would work, for example. So based on sugestions of both of you, I tried the following, which seems to do what I wanted: class Icon(models.Model): ident = models.AutoField(primary_key=True) filename = models.CharField(maxlength=100) class Users(models.Model): ident = models.AutoField(primary_key=True) icon = models.ForeignKey(Icon,blank=True,db_column='icon') class Meta: db_table = 'users' class Admin: pass def save(self): try: print 'saving...' if self.icon: pass except ObjectDoesNotExist: print 'icon does not exists' self.icon = Icon(ident=-1) super(Users, self).save() # Call the "real" save() method. This code does what I want in the admin interface: saving a user without choosing an icon will lead to a user with a icon field = -1 in the database, but which does not refer to any icon in the database. Otherwise, all normal ForeignKey functionality seems to be there. (I can choose to have an icon in my database, with icon.ident=-1, and it will show up in the admin interface). I am not very secure about this code, but it seems to work. Thank you very much, -- Ewout ter Haar --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~----------~----~----~----~------~----~------~--~---