2017-09-19 37 views
0

我正在編寫django中的博客引擎,主要是作爲教育練習,我想知道如何實現多部分博客文章/系列。實現文章系列/多部分博客文章的理想方式

我在python3/django中工作,所以我的代碼將會這樣,儘管我主要關心的是如何正確地實現數據庫結構。鑑於這種通用模式:

class Article(models.Model): 
    title = models.Charfield(255) 
    content = models.TextField() 

我的第一個想法是簡單地添加了一系列的表,並將其鏈接到相應的文章:

class Article(models.Model): 
    title = models.Charfield(255) 
    content = models.TextField() 
    series = models.ForeignKey('Series') 


class Series(models.Model): 
    title = models.Charfield(255) 

,來了下一這裏是如何跟蹤帖位置的問題和系列長度(即:4的2)。我想過如何使用系列條目ID或發佈日期,但我無法保證這些會按照與帖子相同的順序進行。

我可以簡單地跟蹤文章列表上的內容。然後,我可以在系列對象上使用.count()作爲系列長度,並直接從字段中獲取文章位置:它看起來並不像以前那樣優雅:

class Article(models.Model): 
    title = models.Charfield(255) 
    content = models.TextField() 
    series = models.ForeignKey('Series') 
    part = models.PositiveIntegerField() 

然後我想到了製作一個第三個表是誰的行將各自反映了一系列的文章:

class Article(models.Model): 
    title = models.Charfield(255) 
    content = models.TextField() 

class Series(models.Model): 
    title = models.Charfield(255) 

class ArticleSeriesEntry(models.Model): 
    article = models.OneToOneField('Article', related_name='series_info') 
    series = models.ForeignKey('Series', related_name='entries') 
    part = models.PositiveIntegerField() 

我最終喜歡被體健,只是有點訪問信息是這樣的:

{% if article.series is not None %} 
    This post as part {{?}} in a {{?}} part series titled {{?}} 
    View previous post {{?}}, view next post {{}} 
{% endif %} 

我覺得有必要有更好的方法。在此先感謝

回答

1

您的方法只有兩個模型就足夠了。第三種模式 - ArticleSeriesEntry並不真正起任何作用。所以,我會拋棄它。

關於如何獲得下一個或以前的帖子在系列中,我創建了Article模型兩種方法來做到這一點:

class Article(models.Model): 
    # ... other fields ... 
    part = models.PositiveIntegerField() 

    def prev_part(self): 
     try: 
      prev_part = Article.objects.get(series=self.series, part=self.part-1) 
     except Article.DoesNotExist: 
      prev_part = None 
     return prev_part 

    def next_part(self): 
     try: 
      next_part = Article.objects.get(series=self.series, part=self.part+1) 
     except Article.DoesNotExist: 
      next_part = None 
     return next_part 

    def get_absolute_url(self): 
     # this should return url for the given article 
     # see docs: https://docs.djangoproject.com/en/1.11/ref/models/instances/#get-absolute-url 
     pass 
在模板

然後:

{% if article.series %} 
    This post is part {{ article.part }} in a {{ article.series.article_set.count }} part series titled {{ article.series.title }} 

    {% if article.prev_part %} 
     View previous post: <a href="{{ article.prev_part.get_absolute_url }}">{{ article.prev_part.title }}</a> 
    {% endif %} 

    {% if article.next_part %} 
     View next post: <a href="{{ article.next_part.get_absolute_url }}">{{ article.next_part.title }}</a> 
    {% endif %} 
{% endif %}