1

I have a simple to-do list with activities that can be ordered by the user. I use the model List, with a many-to-many field to the model Activities.

Now I need a way to store the user defined ordering of the activities on the list. Should I go with an extra field in my List model to store the order of my activity primary keys like this:

class List(models.Model):
    activities = models.ManyToManyField(Activity)
    order = models.CommaSeperatedIntegerField(max_length=250)

Or should I go with a solution in the Activity model, like described here: https://djangosnippets.org/snippets/998/

What method can be considered as best practice?

JacobF
  • 2,305
  • 3
  • 24
  • 36

1 Answers1

0

you can create your own ManyToMany Model defining the extra field order

https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

something like:

class ActivityList(models.Model):
   activity = models.ForeignKey(Activity)
   list = models.ForeignKey(List)
   order = models.IntegerField()

class List(models.Model)
  activities = models.ManyToManyField(Activity, through='ActivityList')

Now I need a way to store the user defined ordering of the activities on the list.

Specifying and order field allows you to give each activity an order.

specifying a comma seperated string, is 100% not the way to go, IN fact it is one of the biggest anti patterns in relational databases, Is storing a delimited list in a database column really that bad?

Using a through model lets you query for the order when presenting your todo list to the user

for activity in your_list.activities.all().order_by('order'):
   # display activity to user
Community
  • 1
  • 1
dm03514
  • 54,664
  • 18
  • 108
  • 145
  • I'm aware of that, and I'm actually already using a `through` for the activities. But why is that easier or better than a list field in the `List` model? – JacobF Dec 03 '13 at 15:56
  • On a side note, is it correct to name one of the models `List`, since it is also a function? – JacobF Dec 04 '13 at 14:07