更新时间:2023-11-22 12:44:46
您可以覆盖 save $您的
modelB
模型的c $ c>方法,而不是提供默认值:
You can override the save
method of your modelB
model instead of providing a default value:
class ModelB(models.Model):
modela = models.OneToOneField(ModelA)
b_b = models.CharField(max_length=6, choices=[(1, 'M'), (2, 'F')], blank=True)
def save(self, *args, **kwargs):
if not self.b_b:
self.b_b = self.modela.a_b
super(ModelB, self).save(*args, **kwargs)
如果您只想向参观者显示价值,但想保留事实上, ModelB.b_b
是空的,逻辑应该放在模板中。
If you just want to display the value to visitors but want to keep the fact that the ModelB.b_b
is empty, the logic should lay in the template.
假设你的视图集 objB
在上下文中,您有兴趣显示的 ModelB
对象,相关模板的一部分应该如下所示:
Assuming your view set objB
in the context being the ModelB
object your are interested to display, the relevant part of the template should look like:
{% with objB.b_b as bValue %}
{% if not bValue %}
<p>{{ objB.modela.a_b }}</p>
{% else %}
<p>{{ bValue }}</p>
{% endif %}
{% endwith %}