How to model one-to-one relationships in Django

I want to model an article with revisions in Django:

My models.py article has the following:

class Article(models.Model):
    title = models.CharField(blank=False, max_length=80)
    slug = models.SlugField(max_length=80)

    def __unicode__(self):
        return self.title

class ArticleRevision(models.Model):
    article = models.ForeignKey(Article)
    revision_nr = models.PositiveSmallIntegerField(blank=True, null=True)
    body = models.TextField(blank=False)

In the artlcle model, I want to have two direct links to the revision - point to the published revision, and the other to the revision, which is being actively edited. However, from what I understand, OneToOne and ForeignKey links generate a backlink on the other side of the model link, so my question is how to create a one-to-one one-to-one link in Django?

Is there any special spell for this, or do I need to fake it by including state in the revision and custom implementations of fields that request revision in a certain state?

: , . :

, , , "" .

, " " ( ForeignKey(Article) ArticleRevision) : published_revision edited_revision.

, Django ORM.

+3
2

, Django, . , "--" "" , , , .

, . , , Django , related_name, _unused_1. , :

class Article(models.Model):
    title = models.CharField(blank=False, max_length=80)
    slug = models.SlugField(max_length=80)
    revision_1 = models.OneToOneField(ArticleRevision, related_name='_unused_1')
    revision_2 = models.OneToOneField(ArticleRevision, related_name='_unused_2')

    def __unicode__(self):
        return self.title

, , "--" ( - ), , , , . , ForeignKey ArticleRevision, ( ArticleRevision , -, ) Revision, , .

+4

, ? , OneToOneField . , ? , ?

+4

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


All Articles