【问题标题】:How Do I order a Django model by name?如何按名称订购 Django 模型?
【发布时间】:2021-07-21 15:07:49
【问题描述】:

我有一份来自不同零售商的产品清单。我正在尝试对列表进行排序,以尝试将所有相同但具有不同零售商的产品组合在一起。我正在尝试按“产品”对模型进行排序,以便它在 Django admin 面板中按顺序显示,以便我可以立即对产品组执行命令。我该怎么做呢?

型号:

class RetailerProduct(models.Model):
    url = models.CharField(max_length=300,null=True,blank=True) 
    price =  models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True)
    difference = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True)
    retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE)
    available = models.BooleanField(default=False)
    _id = models.AutoField(primary_key=True, editable=False)
    product = models.ForeignKey(Product, on_delete=models.CASCADE,related_name='sources')


    def __str__(self):
        return self.retailer.name + " - " + self.product.name 

我尝试过使用:

class Meta:
    ordering = ('product',)

但它不起作用。

感谢大家的贡献

【问题讨论】:

标签: python django django-models django-rest-framework


【解决方案1】:

您是否在将元数据放入 models.py 文件后进行了迁移?如果您这样做了,但仍然无法正常工作,您可能需要自己创建一个管理员视图。

在 admin.py 中,试试这个:

class RetailerProductAdmin(admin.ModelAdmin):
    ordering = ["product"]
admin.site.register(RetailerProduct, RetailerProductAdmin) 

确保您尚未注册 RetailerProduct。另外,确保在 admin.py 中导入了 RetailerProduct。

【讨论】:

    【解决方案2】:

    views.py内,你可以试试下面的代码,用有序数据创建一个字典并传递字典

    from .models import your_model_name
    def Meta(request):
        ordered_data = your_model_name.objects.order_by('product')
        context = {
            'data': ordered_data
        }
        return render(request, 'your.html', context)
    

    要反转,请添加“-”符号。试试这些

    from .models import your_model_name
    def Meta(request):
        ordered_data = your_model_name.objects.order_by('-product')
        context = {
            'data': ordered_data
        }
        return render(request, 'your.html', context)
    

    过滤数据:

    from .models import your_model_name
    def Meta(request):
        ordered_data = your_model_name.objects.order_by('-product').filter(your_filter==True)
        context = {
            'data': ordered_data
        }
        return render(request, 'your.html', context)
    

    【讨论】:

      猜你喜欢
      • 2019-10-03
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      相关资源
      最近更新 更多