Many to many relationships in the Django model

I am writing a small website to store the documents that I wrote. Relationship documentation is important, but the order of the authors name (which is the First author, which is the second order, etc.) is also important.

I am just learning Django, so I don’t know much. Anyway, 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 is wonderful in the sense that now I can determine who the authors are. But I can’t order them. How can I do it?

Of course, I could add a number of relationships: the first author, the second author, ... but that would be ugly and not flexible. Any better idea?

thanks

+4
source share
1 answer

You can add a 'through' model to these ManyToMany relationships and in this model save a value that indicates the order in which the author should come in this particular connection with the publication.

(Bonus tip - this can help you go down the line - in terms of clarity - use the initial capital letters for class / model names and keep lowercase letters for attributes and instances / objects - this way, if you use the code with others, it will be easier , since this is a common template)

+6
source

Source: https://habr.com/ru/post/1310673/


All Articles