外键的ModelForm的下拉框不是按字母顺序排列的

时间:2015-11-10 04:14:40

标签: django python-3.x

我在" ReviewComments"中创建了一个外键字段。模型并包含命令" order_with_respect_to"。但是,网页中显示的下拉框不会按字母顺序对服务提供商进行排序。是否有代码丢失的东西?

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}),
        }

1 个答案:

答案 0 :(得分:2)

order_with_respect_to不是您想要的。这会针对相应的ReviewComments订购ServiceProvider - 它不会改变ServiceProvider的顺序。

如果您希望按字母顺序列出服务提供商,则需要在ServiceProvider模型上设置默认ordering,指定您要订购的字段:

class ServiceProvider(models.Model):

    # ...

    class Meta:
        ordering = ['individual_name']