Get django default model field value to be a parent attribute value

25 views
Skip to first unread message

Matlau Issu

unread,
Nov 16, 2014, 7:22:34 AM11/16/14
to django...@googlegroups.com
I want the default modB localField value to be the modA wantedField value corresponding to the foreign key. This would gives :

    class modA(models.Model):
        wantedField = models.CharField(max_length=9)
        [ ... other fields ...]
        def asDefault():
            return wantedField

    class modB(models.Model): 
        moda        = models.ForeignKey(modA)
        [ ... other fields ...]
        localField  = models.CharField(max_length=9,default=moda.asDefault)
        def save(self, *args, **kwargs):
            if self.pk is None:
                if self.moda and not self.localField:
                    self.localField = self.moda.wantedField
            super(modB, self).save(*args, **kwargs)

Also, would the approach be the same with any other field type ?
Anyway, for the moment it returns:

    AttributeError: 'ForeignKey' object has no attribute 'asDefault'

Thanks for your help

Collin Anderson

unread,
Nov 17, 2014, 4:45:36 PM11/17/14
to django...@googlegroups.com
Hello,

The issue is with the "default=moda.asDefault". That won't work in this case. If you remove that, does your save method do what you are trying to do?

Collin
Reply all
Reply to author
Forward
0 new messages