updating field in admin change list

I have a model of products, and want to display the list on the admin site with the possibility of changing the order.

class Product(models.Model):
    name = models.CharField(max_length=500)
    is_active = models.BooleanField(default=True)
    category = models.ForeignKey(
        "categories.Category", on_delete=models.CASCADE, related_name="products"
    )
    description = models.TextField(null=True, blank=True)
    ingredient = models.TextField(null=True, blank=True)
    order = models.PositiveIntegerField(default=0)
    rank = models.PositiveIntegerField(default=0)
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0)

    objects = ProductManager()

    class Meta:
        verbose_name_plural = _("Products")
        verbose_name = _("Product")
        ordering = ["order"]

    def __str__(self) -> typing.Text:
        return self.name

I decided to order the model by the field order which can’t be editable in admin page, so I want to copy it’s value to the field rank which I want to make editable in admin page, and when I will save the changes I made to rank I want to override the order values with the new value from rank.
This is how I register the model:

class ProductAdmin(SortableAdminMixin, TranslationAdmin):

    def get_queryset(self, request):
        qs = super(ProductAdmin, self).get_queryset(request)
        for obje in qs.values():
            rank = obje["order"]
            obje["rank"] = rank
        return qs

    inlines = [ImagesInline, NutritionsInline]
    search_fields = ["name", "description"]
    autocomplete_fields = ["category", "brand", "manufacturer"]
    fieldsets = (
        (
            _("Details"),
            {
                "fields": (
                    "is_active",
                    "name",
                    "price",
                    "category",
                    "description",
                ),
            },
        ),
        (
            _("Product Info"),
            {
                "fields": ("ingredient",),
            },
        ),
    )
    list_display = ("order", "rank", "name", "category")
    list_editable = ["rank"]

I tried to override the get_queryset but it didn’t work.
have you any idea how to do this?

Is this post a duplicate of your post here: reordering change list in admin page? If so, please don’t repeat posts. If you have additional information for your original question, you can edit that post (or supply a comment on it) to include the updated information.

I had a different Idea to do what I wanted. I’ll delete the previous post, is it ok ?

Yep, that works too. Or, if there is a difference, leaving them both is fine too. It just helps to avoid confusion if there’s only one topic for a particular issue.

1 Like