[英]Django - Get Default value from another Model Field
I came across this strange problem in django where I have 3 models Books, Language, Book_language
where i map book to its language. 我在django遇到了一个奇怪的问题,我在这里有3种模型
Books, Language, Book_language
,我将book映射到其语言。
from django.db import models 从django.db导入模型
class Book(models.Model):
title = models.CharField(max_length=200)
year = models.IntegerField()
class Language(models.Model):
name = models.CharField(max_length=50)
class Book_language(models.Model):
book = models.ForeignKey(Book)
language = models.ForeignKey(Language)
other_title = models.CharField(max_length=200, default=Book._meta.get_field('title').get_default()) # not working
So far i am creating a book and with title and later assigning with language so the title is same for all languages, later i understand that the title may not be the same in all languages, so i want other_title
to be default to title
if not mention ( but not working
), and appear in django admin when i map with language. 到目前为止,我正在创建一本书并带有标题,后来分配了语言,因此所有语言的标题都是相同的,后来我了解到标题在所有语言中可能都不相同,因此我希望
other_title
缺省为title
如果不是提及( but not working
),并且当我使用语言映射时出现在django admin中 。
can you simple override save
method? 您可以简单地覆盖
save
方法吗?
class Book_language(models.Model):
book = models.ForeignKey(Book)
language = models.ForeignKey(Language)
other_title = models.CharField(max_length=200)
def save(self, *args, **kwargs):
if not self.other_title:
self.other_title = self.book.title
super(Book_language, self).save(*args, **kwargs)
for updating-multiple-objects-at-once previous empty data you can use expressions F : 要一次更新多个对象以前的空数据,可以使用表达式F :
from django.db.models import Q, F
empty_f = Q(other_title__isnull=True) | Q(other_title__exact='')
for bl in Book_language.objects.filter(empty_f):
bl.other_title = bl.book.title
bl.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.