2017-10-08 216 views
1

我在Django中遇到了这个奇怪的问题,其中 我有3个模型Books, Language, Book_language在哪里我将书籍映射到它的语言。Django - 从另一个模型字段获取默认值

从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 

到目前为止我创建的书,用的标题,后来与语言分配等多项称号同是所有语言,后来我明白,内容可能不会出现所有语言都一样,所以我想other_title默认为title,如果没有提及(but not working)和出现在django管理员当我与语言映射。

回答

0

你能简单地覆盖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) 

updating-multiple-objects-at-once以前空的数据,可以使用expressions 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() 
+0

感谢,1)'ther_title'代替other_title'的''中= self.ther_title预期self.book.title'或错字,2)'Book._meta.get_field('title')。get_default()'3)有什么问题?以前我有数据,如何迁移,以使'other_title'不会为先前记录为空。 – Srinivas

+0

1.是的,这是一个错字,2.我不知道它为什么应该工作,为3我更新了答案 –

+0

谢谢布朗... – Srinivas

相关问题