Django: fill model's fields with values from another model (at init and save)

为君一笑 提交于 2019-12-12 10:23:08

问题


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)


来源:https://stackoverflow.com/questions/25326619/django-fill-models-fields-with-values-from-another-model-at-init-and-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!