Pietro Speroni
Pietro Speroni

Reputation: 3221

Order in many to many relation in Django model

I am writing a small website to store the papers I have written. The relation papers<-> author is important, but the order of the name of the authors (which one is First Author, which one is second order, and so on) is also important.

I am just learning Django so I don't know much. In any case so far I have done:

from django.db import models

class author(models.Model):
    Name = models.CharField(max_length=60)
    URLField = models.URLField(verify_exists=True, null=True, blank=True)

    def __unicode__(self):
        return self.Name

class topic(models.Model):        
    TopicName = models.CharField(max_length=60)
    def __unicode__(self):
        return self.TopicName

class publication(models.Model):
    Title           = models.CharField(max_length=100)
    Authors         = models.ManyToManyField(author, null=True, blank=True)
    Content         = models.TextField()
    Notes           = models.TextField(blank=True)
    Abstract        = models.TextField(blank=True)
    pub_date        = models.DateField('date published')
    TimeInsertion   = models.DateTimeField(auto_now=True)
    URLField        = models.URLField(verify_exists=True,null=True, blank=True)
    Topic           = models.ManyToManyField(topic, null=True, blank=True)

    def __unicode__(self):
        return self.Title

This work fine in the sense that I now can define who the authors are. But I cannot order them. How should I do that?

Of course I could add a series of relations: first author, second author,... but it would be ugly, and would not be flexible. Any better idea?

Thanks

Upvotes: 4

Views: 3189

Answers (1)

Steve Jalim
Steve Jalim

Reputation: 12195

You could add a 'through' model to that ManyToMany relationship and in that model, store a value that shows the order the Author should come in this particular association with a Publication.

(Bonus tip - it might help you down the line - in terms of clarity - to use initial capital letters for class/model names and keep lowercase for attributes and instances/objects - that way if you're sharing code with others, it'll be easier as it's a common pattern)

Upvotes: 6

Related Questions