2016-05-11 17 views
0

次のように別のオブジェクトからの値を使用しようとしています。だから私は、インパクトフィールドから選択するメンテナンスタイプの事前定義セットリストを持っています。私はこのモデルを作成しようとすると、私はエラーにdjangoモデルでは、別のオブジェクトからの値を選択肢として使用します

[[email protected] infternal]# python manage.py makemigrations maintenance 
SystemCheckError: System check identified some issues: 

ERRORS: 
maintenance.Maintenance.Impact: (fields.E004) 'choices' must be an iterable (e.g., a list or tuple). 

モデルの設定

class MaintenanceType(models.Model): 
    Type = models.CharField(max_length=200) 

    class Meta: 
       verbose_name = "Planned Maintenance Types" 
       verbose_name_plural = "Planned Maintenance Types" 

class Maintenance(models.Model): 
    Title = models.CharField(max_length=200) 
    Impact = models.CharField(max_length=200, choices=MaintenanceType) 
    Description = models.TextField() 
    StartTime = models.DateTimeField 
    EndTime = models.DateTimeField 

    class Meta: 
       verbose_name = "Planned IT Maintenance" 
       verbose_name_plural = "Planned IT Maintenance"  
+5

'ForeignKey'は、おそらくここでより良い選択である:'インパクト= models.ForeignKey(MaintenanceType) '。 – Alasdair

答えて

2

を得る 'のForeignKey'は、よりよい解決策です。以下のコードも試してみてください。

models.py

Impact = models.CharField(max_length=200) 

forms.py

class MaintenanceForm(ModelForm): 
    def __init__(self, *args, **kwargs): 
     super(MaintenanceForm, self).__init__(*args, **kwargs) 
     self.fields['Impact'].choices = list(MaintenanceType.objects.values_list('id', 'Type')) 


    class Meta: 
     model = Maintenance 
+1

私はこれが新しいメンテナンスタイプを一度だけ呼び出すので(これまでこれを得ることができれば) – Sayse

+0

@Alasdair、更新された回答を含むことはないと確信しています。これがうまくいくと思います:) – Anoop

+0

これはまだ正しくはありません。クエリーセットではなくタプルのリストに選択肢を設定する必要があります。あなたは 'value_list'を使うことができます。 'self.fields ['Impact']。choices = MaintenanceType.objects.all()。values_list( 'Type'、 'Type')'。 – Alasdair

関連する問題