2015-11-10 62 views
0

我在「ReviewComments」模型中創建了一個外鍵字段,幷包含命令「order_with_respect_to」。但是,網頁中顯示的下拉框不會按字母順序對服務提供商進行排序。有沒有代碼丟失的東西?ModelForm的外鍵下拉框不按字母順序排列

Models.py

class ServiceProvider(models.Model): 
    identification_number = models.AutoField(primary_key=True,) 
    license_number = models.CharField(max_length=10, null=True, blank=True,) 
    individual_name = models.CharField(max_length=60,) 
    corporate_name = models.CharField(max_length=120,) 
    reg_address = models.CharField(max_length=180,) 
    email_address = models.EmailField(max_length=254, null=True, blank=True,) 
    land_line = models.CharField(max_length=50, null=True,) 
    hand_phone_line = models.CharField(max_length=50, null=True, blank=True,) 
    service_type = models.CharField(max_length=20) 

    def __str__(self): 
     return "%s (%s)" % (self.individual_name, self.service_type) 

class ReviewComments(models.Model): 
    comment_id = models.AutoField(primary_key=True) 
    title = models.CharField(max_length=120) 
    comment = models.CharField(max_length=250) 
    receipt_document = models.FileField(upload_to='receipt_document', default=None,) 
    service_provider = models.ForeignKey(ServiceProvider, on_delete=models.CASCADE) 
    user_id = models.CharField(max_length=10, null=True, blank=True,) 

    class Meta: 
     order_with_respect_to = 'service_provider' 

    def __str__(self): 
     return self.title + "\n" + self.comment 

Forms.py

class ReviewForm(ModelForm): 
    class Meta: 
     model = ReviewComments 
     fields = ['title', 'comment', 'service_provider', 'receipt_document', ] 
     widgets = { 
      'title': Textarea(attrs={'cols': 80, 'rows': 1}), 
      'comment': Textarea(attrs={'cols': 80, 'rows': 10}), 
     } 

回答

2

order_with_respect_to是不是你在找什麼。這將命令您的ReviewComments相對於其相應的ServiceProvider - 它不會改變ServiceProvider的順序。

如果你希望你的服務提供商將字母順序列出,那麼你需要設置默認ordering上的ServiceProvider模型,指定你想訂購的字段:

class ServiceProvider(models.Model): 

    # ... 

    class Meta: 
     ordering = ['individual_name'] 
+0

謝謝!這讓我瘋狂! – Cloud