'Django retain order of product when displayed

Suppose I want the order of my products in my Django webshop to be displayed in a certain order. How can I achieve that? I have simplified the below example to show the problems that I am experiencing. In my webshop models I have the below 2 models.

class TakeawayWebshop(models.Model):
    name = models.CharField(max_length = 255, help_text = 'name of takeaway restaurant')
    products = models.ManyToManyField(Product)

class Product(models.Model):
    name = models.CharField(max_length = 50, unique=True)
    description = models.TextField()
    price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00)

    class Meta:
        ordering = ['-created_at']

In the admin.py I have

class TakeawayWebshopAdmin(admin.ModelAdmin):
    form = TakeawayWebshopAdminForm
    list_display = ['name']
    ordering = ['name']
    filter_horizontal = ('products',)

admin.site.register(TakeawayWebshop, TakeawayWebshopAdmin)

Now from the admin, I am adding 3 products in the exact order of product A, product B and product C to the webshop using the filter_horizontal. product added the exact order. Upon saving the TakeawayWebshop model object, the products in the filter_horizontal box automatically rearanged, so the order becomes product C, product B and product A.

When from the views.py if I get a list of all the products I have added to the webshop such as

webshop = TakeawayWebshop.objects.filter(name = 'my webshop name')[0]
products = webshop.products.all() 

The queryset returned is

<QuerySet [<Product: Product C>, <Product: Product B>, <Product: Product A>]>

Obviously I guess I am using the wrong strategy in trying to make the products in query set appear in the order that I originally intend them to be arranged (product A, product B and product C) when inserting them into the filter_horizontal box. Also I am wondering if it is possible to rearrange the order that products in filter_horizontal box appear?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source