Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain insert ordering for one-to-many relationship in Django

How to maintain insert ordering with one-to-many Django mapping, for eg: Say we have,

class Person(models.Model):
    name = Model.CharField(max_length=50)

class Subject(models.Model):
    sub_name = Model.CharField(max_length=50)
    person = Model.ForeignKey('Person')

def insert_data():
    person = Person.objects.create(name='Deepan')
    Subject(name='Eng', person=person).save()
    Subject(name='Sci', person=person).save()

Subject.objects.filter(person=person) # is there a way to make this to always return the subjects in the inserted order, i.e Eng, Sci instead of Sci, Eng

This is handled using list types in hibernate/grails

like image 319
Deepan S Avatar asked Dec 28 '10 09:12

Deepan S


People also ask

How do I add a one to many relationship in Django?

To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).

What is ManyToManyField in Django?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.


2 Answers

Define the ordering using meta info:

class Subject(models.Model):
    sub_name = models.CharField(max_length=50)
    person = models.ForeignKey('Person')
    time = models.DateTimeField(auto_now_add = True)

    class Meta:
        ordering = ['time'] #or ['-time'] according to the ordering you require

This will save the creation datetime in the time field and hence the results will be ordered according to addition time.

btw (if there are some other reasons) from your models it seems there will be many Persons and many Subjects so I suggest using many to many fields. This will map multiple users to multiple subjects and symmetrically back. You may even use the through option to store more details (time etc for sorting, even marks/percentage for storing records if you require to do that) per Person-Subject mapping.

like image 72
crodjer Avatar answered Oct 05 '22 11:10

crodjer


You need to use a meta class to always sort it and use a date time field with the auto_now option set to True.
I recommend using a proxy class for the sorting. Sorting is an expensive operation.
See this link for more details on sorting and this link on proxy models.

like image 22
the_drow Avatar answered Oct 05 '22 12:10

the_drow