Django: fill model's fields with values from a

2019-06-10 07:00发布

问题:

I've got 2 models (for the example).

class A(models.Model):
    name = models.CharField()

class B(models.Model):
    a = models.ForeignKey(A)
    my_name = models.CharField()

So, I want to create (and update) the field my_name of the instance of B, with the field name of the instance of A to which it's related (one to many relation).

I've tried:

class B(models.Model):
    ....
    def __init__(self, *args, **kwargs):
       self.my_name = self.a.name

But I've got the error:

AttributeError
Exception Value:    
'B' object has no attribute 'a_id'

I think it's something related to Django adding a _id for foreign key field, so I've tried :

class B(models.Model):
    a = models.ForeignKey(A, db_column="a")
    ...

But I've got the same error.

I'm pretty new to Django. Thx!

回答1:

Try overriding the save method on your B model:

class B(models.Model):
    a = models.ForeignKey(A)
    my_name = models.CharField()

    def save(self, *args, **kwargs):
        self.my_name = self.a.name
        super(B, self).save(*args, **kwargs)