一千萬個為什麽

搜索

ContentType問題 - 人類是一個白癡 - 無法弄清楚如何將原始模型與ContentType抽象的“收藏”模型聯系起來

Originally started here: Django IN query as a string result - invalid literal for int() with base 10

我的網站中有許多應用,目前正在使用簡單的“博客”應用。我開發了一個“最喜歡的”應用程序,很容易,利用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文檔在這裏:反向通用關系。基本上在Blog模型本身上你可以添加 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()

轉載註明原文: ContentType問題 - 人類是一個白癡 - 無法弄清楚如何將原始模型與ContentType抽象的“收藏”模型聯系起來