python - 模型继承和RSS Feed框架

标签 python django inheritance rss feed

我使用模型继承来管理多个模型查询集:

from django.db import models
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
from imagekit.models import ImageModel
import datetime

class Entry(models.Model):
    date_pub = models.DateTimeField(default=datetime.datetime.now)
    author = models.ForeignKey(User)
    via = models.URLField(blank=True)
    comments_allowed = models.BooleanField(default=True)

    class IKOptions:
        spec_module = 'journal.icon_specs'
        cache_dir = 'icon/resized'
        image_field = 'icon'


class Post(Entry):  
    title = models.CharField(max_length=200)
    description = models.TextField()
    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.title


class Photo(Entry):
    alt = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    original = models.ImageField(upload_to='photo/')    

    def __unicode__(self):
        return self.alt


class Quote(Entry):
    blockquote = models.TextField()
    cite = models.TextField(blank=True)

    def __unicode__(self):
        return self.blockquote

条件模板足以使用基于 Entry.objects.all() 的 View 呈现正确的 html 片段:

{% extends "base.html" %}
{% block main %}
<hr>
{% for entry in entries %}

{% if entry.post %}
[...do something with entry.post]
{% endif %}

{% if entry.photo %}
[...do something with entry.photo]
{% endif %}

[...and so on]

现在我正在尝试使用 Django 1.2 中的新 Feed 框架生成 RSS feed,但没有任何运气...该框架的过于简化的设置不允许我指定条件 item_titleitem_description 基于 Entry 的子对象:

from django.contrib.syndication.views import Feed
from totanus.journal.models import Entry, Photo, Post, Quote


class LatestEntriesFeed(Feed):
    title = "RSS Feed"
    link = "/journal/"
    description = "Journal RSS"

    def items(self):
           return Entry.objects.order_by('-date_pub')[:10]

    def item_title(self, item):
           # if child is Post
           return item.post.title # this isn't working, of course...

我应该创建一个自定义 View 模板集来管理 RSS 创建和聚合,还是有办法将 Feed 框架与此子类模型结合使用?

最佳答案

您有两个选择:

  1. 使用 Feed 类上的 title_templatedescription_template 属性来指向可以处理非常通用的输入变量的模板。

  2. 在 Feed 类的方法中重新创建模板逻辑,以便您的模板变量获得规范化的数据。

任何一个都会让您达到相同的终点。

关于python - 模型继承和RSS Feed框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3040818/

相关文章:

python - 如何在 Python 中访问 SoundCloud-Stream URL?

python - 以预定义的宽度/高度比保存右侧带有图例的 matplotlib 图

python - Django 上静态 STATIC_URL 和 STATIC_ROOT 之间的区别

ruby - HAML 继承

javascript - 了解 JS 中的原型(prototype)继承方法

python - 从 GDAL 中的栅格中提取点

python - C通过系统调用执行python脚本

c++ - 在不使用虚函数的情况下覆盖对 C++ 中基类的调用?

python - Django 和 Oracle DB 失去联系

如果缺少 csrf cookie,Django 1.6 HTTP_X_CSRFTOKEN header 将被忽略