iducam
iducam

Reputation: 79

How do I use abstract model field values as default values in child model fields in Django?

For example,

class Foo(models.Model):
    foo_field = models.CharField(max_length=30)

    class Meta:
        abstract = True


class Bar(Foo):
    bar_field = models.CharField(max_length=30, default=Foo.foo_field)

    def __str__(self):
        return self.name

This code doesn't actually produce the results I want, but I think it illustrates the general idea. Basically, I want to take the value from foo_field and use it as a default value if no value is entered for bar_field.

I've tried returning foo_field with a ___str___ method in the Foo model and defining a variable in Bar with that value (i.e. foo_field_value = Foo.foo_field, but that didn't allow me to access the value either.

Upvotes: 0

Views: 298

Answers (1)

rgermain
rgermain

Reputation: 708

many possible solution

in save:

def save(self):
   if not self.bar_field:
      self.bar_field = self.foo_field
   super().save()

define methods:

  def get_bar_field(self):
      return self.bar_field or self.foo_field

signals:

@receiver(pre_save, sender=Bar)                                        
def assign_default_bar_field(sender, instance, **kwargs):                                 
   if not instance.bar_field:
       instance.bar_field = instance.foo_field

define clean methods:

def clean(self, data):
   if not 'bar_field' in data or not data['bar_field']:
      data['bar_field'] = data['foo_field']
   return data

Upvotes: 1

Related Questions