本文介绍了Django:使用来自另一个模型的值填充模型的字段(在初始化和保存时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个模型(例如)。

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()

因此,我想创建(并更新)字段 my_name B的实例,并与它相关的A的实例的字段 name (一对多关系)。

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).

我尝试过:

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

但是我遇到了错误:

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

我认为这与Django添加有关一个 _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")
    ...

但是我

我对Django很陌生。

I'm pretty new to Django. Thx!

推荐答案

尝试在<$ c上覆盖 save 方法$ c> B 模型:

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)

这篇关于Django:使用来自另一个模型的值填充模型的字段(在初始化和保存时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 05:44