2017-10-08 128 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

相關問題