2016-03-19 20 views
1

私はPython 3.3とDjango 1.9を使用しています。私は私のDjangoのモデルに多言語サポートを実装する必要があるので、私は重複フィールドを作成することを決めた - 例えば:Django動的モデル作成。フィールドが衝突しています

class Header:  
    ua_title = models.CharField(max_length=100) 
    ru_title = models.CharField(max_length=100) 
    en_title = models.CharField(max_length=100) 
    ua_subtitle = models.CharField(max_length=100) 
    ru_subtitle = models.CharField(max_length=100) 
    en_subtitle = models.CharField(max_length=100) 

私は多くの分野で、このような多くのモデルを持っているので、私はそれらを動的に作成することを決めました。私は下の関数を書いた:

def create_language_dependent_model(model_name: str, attrs: dict) -> models.Model: 

    DEFAULT_LANGS = ('ua', 'ru', 'en') 

    result_attrs = { 
     '__module__': 'app.models' 
    } 

    for attribute_name, options in attrs.items(): 
     if options.get('isLanguageDependent'): 
      for lang in DEFAULT_LANGS: 
       result_attrs[lang + "_" + attribute_name] = options.get('field_type') 
     else: 
      result_attrs[attribute_name] = options.get('field_type') 

    return type(
     model_name, (models.Model,), result_attrs 
    ) 

そして、私はこのようなモデルを作成:

Header = create_language_dependent_model("Header", { 
    attr_name: {'isLanguageDependent': True, 'field_type': models.CharField(max_length=100)} 
     for attr_name in ('title', 'subtitle') 
    }) 

しかし、私はmakemigrationsを実行しようとすると、私は次のエラーを取得:

.... 
app.Header.ru_title: (models.E006) The field 'ru_title' clashes with the field 'ru_title' from model 'app.header'. 
app.Header.ru_title: (models.E006) The field 'ru_title' clashes with the field 'ru_title' from model 'app.header'. 
app.Header.en_title: (models.E006) The field 'en_title' clashes with the field 'en_title' from model 'app.header'. 
app.Header.en_title: (models.E006) The field 'en_title' clashes with the field 'en_title' from model 'app.header'. 
.... 

答えて

0

、私は機能を使用してモデルを作成しようとすると、私はfield_typeキーにクラスCharFieldinstanceを渡し、実現。 そして、ループ内の関数create_language_dependent_modelでは、同じインスタンスを別のモデルフィールドに割り当てようとしています result_attrs[lang + "_" + attribute_name] = options.get('field_type')。そのような場合、異なるフィールドはCharFieldの同じインスタンスを参照しているため、結果iにはフィールドの衝突があります。解決策は、フィールドごとにCharFieldの新しいインスタンスを作成することです

0

だろうモデルにlanguageフィールドを追加するオプションがありますか?調査の後

class Header(models.Model):  
    title = models.CharField(max_length=100) 
    subtitle = models.CharField(max_length=100) 
    language = models.CharField(max_length=2, default='en') 
+0

このような場合、私はそのモデルのインスタンスをデータベースに作成する必要がありますが、実際のモデルでは "共通"フィールドはすべてのインスタンスで同じになりますが、その多くはImageFieldとFileFieldですが、CharFieldsの重複がファイルやイメージの複製より優れていると思います。しかし、あなたのポイントは良いです、ありがとう – parikLS

関連する問題