Rol*_*epp 4 python django django-models
I want to model an article with revisions in Django:
I have following in my article's models.py:
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)
Run Code Online (Sandbox Code Playgroud)
On the artlcle model I want to have 2 direct references to a revision - one would point to a published revision and another to a revision that is being actively edited. However from what I understand, OneToOne and ForeignKey references generate a backreference on the other side of the model reference, so my question is, how do i create a one-way one-to-one reference in Django?
Is there some special incantation for that or do I have to fake it by including state into revision and custom implementations of the fields that ask for a revision in specific state?
Edit: I guess, I've done somewhat poor job of explaining my intent. Let's try it on a higher abstraction level:
My original intent was to implement a sort of revisioned article model, where each article may have multiple revisions, where one of those revisions may be "published" and one actively edited.
This means that the article will have one-to-many relationship to revisions (represented by ForeignKey(Article) reference in ArticleRevision class) and two one way references from Article to revision: published_revision and edited_revision.
My question is mainly, how can I model this with Django's ORM.
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
Run Code Online (Sandbox Code Playgroud)
也就是说,一对一关系在应用程序中很少有用(除非您出于某种原因进行优化),我建议您仔细检查您的数据库架构,以确保这确实是您想要的。在您的 ArticleRevision 上保留一个 ForeignKey 字段指向一个文章可能是有意义的(因为 ArticleRevision 可能总是需要与文章相关联)并向 Revision 添加另一列以指示它是否已发布。
| 归档时间: |
|
| 查看次数: |
6630 次 |
| 最近记录: |