我使用模型继承来管理多个模型查询集:
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_title 和 item_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 框架与此子类模型结合使用?
最佳答案
您有两个选择:
使用 Feed 类上的
title_template
和description_template
属性来指向可以处理非常通用的输入变量的模板。在 Feed 类的方法中重新创建模板逻辑,以便您的模板变量获得规范化的数据。
任何一个都会让您达到相同的终点。
关于python - 模型继承和RSS Feed框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3040818/