ContentType 问题 - 人类是个白痴 - 无法弄清楚如何将原始模型与 ContentType 抽象的“最爱”模型联系起来

StackOverflow https://stackoverflow.com/questions/2656637

  •  27-09-2019
  •  | 
  •  

最初是从这里开始的: Django IN 查询作为字符串结果 - 以 10 为基数的 int() 的文字无效

我的网站中有许多应用程序,目前正在使用一个简单的“博客”应用程序。我开发了一个“最喜欢的”应用程序,非常简单,它利用 Django 中的 ContentType 框架来允许我拥有任何类型的“最喜欢的”...试图走另一条路,但是,我不知道我在做什么,也找不到任何例子。

我将从最喜欢的模型开始:

最喜欢的/models.py

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User

class Favorite(models.Model):
        content_type    = models.ForeignKey(ContentType)
        object_id       = models.PositiveIntegerField()
        user            = models.ForeignKey(User)
        content_object  = generic.GenericForeignKey()

        class Admin:
                list_display = ('key', 'id', 'user')

        class Meta:
                unique_together = ("content_type", "object_id", "user")

现在,这允许我循环浏览收藏夹(例如,在用户的“收藏夹”页面上)并通过 {{ favorite.content_object.title }} 获取关联的博客对象。

我现在想要但无法弄清楚的是,我需要对博客模型做些什么,以允许我对收藏夹有一些联系(例如,当它显示在列表中时,它可以突出显示)。

这是博客模型:

博客/models.py

from django.db import models
from django.db.models import permalink
from django.template.defaultfilters import slugify
from category.models import Category
from section.models import Section
from favorite.models import Favorite
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Blog(models.Model):
        title           = models.CharField(max_length=200, unique=True)
        slug            = models.SlugField(max_length=140, editable=False)
        author          = models.ForeignKey(User)
        homepage        = models.URLField()
        feed            = models.URLField()
        description     = models.TextField()
        page_views      = models.IntegerField(null=True, blank=True, default=0 )
        created_on      = models.DateTimeField(auto_now_add = True)
        updated_on      = models.DateTimeField(auto_now = True)

        def __unicode__(self):
                return self.title

        @models.permalink
        def get_absolute_url(self):
                return ('blog.views.show', [str(self.slug)])

        def save(self, *args, **kwargs):
                if not self.slug:
                        slug = slugify(self.title)
                        duplicate_count = Blog.objects.filter(slug__startswith = slug).count()
                        if duplicate_count:
                                slug = slug + str(duplicate_count)
                        self.slug = slug
                super(Blog, self).save(*args, **kwargs)

class Entry(models.Model):
        blog            = models.ForeignKey('Blog')
        title           = models.CharField(max_length=200)
        slug            = models.SlugField(max_length=140, editable=False)
        description     = models.TextField()
        url             = models.URLField(unique=True)
        image           = models.URLField(blank=True, null=True)
        created_on      = models.DateTimeField(auto_now_add = True)

        def __unicode__(self):
                return self.title

        def save(self, *args, **kwargs):
                if not self.slug:
                        slug = slugify(self.title)
                        duplicate_count = Entry.objects.filter(slug__startswith = slug).count()
                        if duplicate_count:
                                slug = slug + str(duplicate_count)
                        self.slug = slug
                super(Entry, self).save(*args, **kwargs)

        class Meta:
                verbose_name = "Entry"
                verbose_name_plural = "Entries"

有什么指导吗?

有帮助吗?

解决方案

django 文档在这里: 反向泛型关系. 。基本上在博客模型本身上,您可以添加 GenericRelation...

class Blog(models.Model):
    favorites = generic.GenericRelation(Favorite)

对于给定的博客,您可以找到所有 Favorite 与之相关的模型...

b = Blog.objects.get(slug='hello-world-blog-slug')
all_blog_favorites = b.favorites.objects.all()

或者查看当前用户是否收藏了该博客...

user_has_blog_favorited = b.favorites.objects.filter(user=request.user).exists()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top