Django Many to Many relationship

There is a many to many relationship in my model. Now my requirement is that as it is a many to many relationship I want to select some objects. For example there are 10 objects in the many to many field. Now if I select the 10th object and then the first it should show in the same order when I save it. Currently it automatically sorts the objects and shows the first object and then the 10th object. I will be attaching a screenshot for reference.


In the screenshot I have shown that there are 3 blogs. My requirement is that If i select the third blog first and the first blog after that. When i save it automatically sorts and puts the first blog at first position and the third at second. I have written screenshot 2 and attached the screenshot within that. Please guide me how can I achieve that in many to many that If whichever object I select first should remain first and it should maintain the order.

Hello there!
You won’t be able to dictate the ordering of the m2m (many-to-many) relationship using the default’s ManyToManyField. You have some options:

  • Using a intermediate model on the ManyToManyField by passing the through option, this is documented here. On that intermediate model, you can create a DateTimeField with the auto_now_add option, so everytime you add a new object this field will be populated. Then you can use this field to define the ordering on the intermediate model Meta class. One thing to keep in mind is that, if you add multiple objects at the same time, they may get randomly ordered within themselves.
  • Using a model that contains the both foreign keys instead of the m2m field. On this model you can have a field named order (or any other name you want) being a IntegerField, and using this field to determine in which order they will be displayed. So in the admin, instead of having this as a field, you would use this model as a inline and will be able to input the order manually for each of the related.

Hope this helps you get on track, cheers!

But I guess then I will have to add each field one by one. If I select all the fields at once it will be again creating conflicts. Correct me if I am wrong here.

The standard multi-select widget is an unordered field. It makes no difference for the sequence being selected.

You’d need to find and implement a JavaScript ordered multiselect field widget. (No, I don’t know of any.)