我有一個包含許多不同內容類型的對象的頁面。我需要有能力評價這個對象。下面是它的一類:Django在模板中獲取ContentType
class Score(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
for_object = generic.GenericForeignKey('content_type', 'object_id')
like = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
comment = models.CharField(max_length=255, blank=True, null=True)
objects = ChainerManager(ScoreQuerySet)
def __unicode__(self):
return u'Score for (%s, #%s) from user %s at %s' %\
(self.content_type, self.object_id, self.user.get_full_name(), self.created_at)
class Meta:
unique_together = (('user', 'content_type', 'object_id'),)
而且我的模板應該是這樣的:
...
{% for random_object in random_object_queryset %}
<a href={% url like_object random_object.<content_type> random_object.id %}>{{ random_object.name }}</a>
<a href={% url dislike_object random_object.<content_type> random_object.id %}>{{ random_object.name }}</a>
{% endfor %}
...
我可以做模板標籤得到它,或者得到一個類名,即使用這段代碼:http://djangosnippets.org/snippets/294/ 我可以重寫這個snuppet來獲取對象的content_type_id,但是我擔心在DB中大量的CT查找。
但是有沒有一種嵌入式的方法來獲取對象的CT模板?
視圖代碼:
def rate_object(request, classname, object_id, like=True):
user = request.user
Klass = ContentType.objects.get(model=classname).model_class()
obj = get_object_or_404(Klass, user=user, pk=object_id)
try:
score = Score.objects.for_object(user, obj)
score.like = like
score.save()
except Score.DoesNotExist:
score = Score.objects.like(user, obj) if like else Score.objects.dislike(user, obj)
return HttpResponse(obj)
你可以把你的視圖代碼? –
僅供參考:您不應在變量之後添加太多空格。這不是PEP8(http://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements) – Thomas