'Sort objects by the date they were added to the ManyToManyfield field - Django

I save the products in ManyToMany field that the user has favored in my web application.

class LikedProductPackage(models.Model):
    owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True)
    products = models.ManyToManyField(Product)

I display my favorite products in the template user like this:

{% for obj in liked_product_package_instance.products.all %}
[...]
{% endfor %}

Is there any option to sort products by the date they were added to the LikedProductPackage.products field in the template or view without changing the of this function too much?



Solution 1:[1]

If 'Product' model has date field then you can use 'order_by' on your products list to sort queryset based on the date field value.

products_list = liked_product_package_instance.products.all().order_by('date_field')
# products_list will have all the 'Product' instances that are in relationship with 'liked_product_package_instance' and sorted based on the 'date_field'. 'date_field' should be present in "Product" model.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 B.Anup