Reference field in parent model from the child in a one-to-many relationships during clean

14 views
Skip to first unread message

David Williamson

unread,
Feb 11, 2018, 8:41:25 AM2/11/18
to Django users
Hi,

I have two fields in a model as follows:

    society_rowid = models.ForeignKey (
        'Organisation', on_delete=models.PROTECT, related_name='society',
        blank=True, null=True, db_column='society_rowid',
        limit_choices_to={'type': 'whatson_society'},
        verbose_name='Society',
    )

    presented_by = models.CharField (
        max_length=50,
        blank=True,
    )

In the admin interface, if the foreign key is selected and the presented_by is empty, then i want to populate presented_by with the value of the name field at the other end of the relationship. I've tried the following in my clean method for the child object.

        if self.society_rowid is not None and self.presented_by is None:
            self.presented_by = str ( self.society )

        if self.society_rowid is not None and self.presented_by is None:
            self.presented_by = self.society__name

        if self.society_rowid is not None and self.presented_by is None:
            self.presented_by = self.society.name

None of these throw an error but neither do they populate the presented_by field. Any ideas?

Thanks

Dave

Daniel Roseman

unread,
Feb 11, 2018, 3:34:57 PM2/11/18
to Django users
Presumably, the condition is not true, which also explains why there is no error; at least one of these, and possibly all of them, should throw AttributeErrors. Are you sure the presented_by field is None, rather than an empty string?

Also you should show the rest of your models. Do you actually have a `society` field, separate from `society_rowid`?
--
DR.
Reply all
Reply to author
Forward
0 new messages