Reputation: 824
I am using jQuery UI Sortable to allow users to sort images that they have uploaded by drag & drop. Here's how it works:
when they upload some pictures, they are directed to another page in which all the newly uploaded images are displayed in a column on the left. Users can drop photos from the left column to the right column in the order they wish. I'm using jQuery Serialize to get the sorted array.
My question is, how can I update my database to re-arrange the images and save the order same as the one returned by Serialize?
Thanks
Upvotes: 2
Views: 1744
Reputation: 1121406
Don't alter the order in your database, have your database sort the results instead. All you need to do is give the database something to sort by.
Add an order
integer field to your model, and update those values when a user has created an order for your images; this is a simple numbering operation. Then when you query for the images for display, sort them on that field.
If images are shared between users, you'd need to make this a separate model; one that maps user to image with the order attached:
class ImageOrder(Model):
"""Keeps track ordering of images for a given user"""
order = IntField()
user = ForeignKey(User)
image = ForeignKey(Image)
Now you can filter images by their relationship to a given user, and order them by the order
field:
ImageOrder.objects.filter(user=user).order_by('order').select_related('image')
then use the .image
field of each ImageOrder
instance.
Upvotes: 4