如何在基于类的视图中调用ManyToManyField

时间:2016-04-24 10:19:23

标签: django

我刚刚在这里打砖块;我不知道发生了什么事?

我想做一个简单的博客。

因此,您可以在下面看到我定义了ManyToManyField并将类别设置为多对多字段,然后将名称相关联。

之前我使用过基于函数的视图,我简单地将其称为相关名称:

例如

def catdetail(request, slug):
code here 
and
posts = category.pots.all() /////and this gave me all posts related to this cateogry,

但是在类别详细信息视图的基于类的视图中,我无法从Post调用此类别字段;我所有的尝试都没有成功;错误,如类别尚未定义,类别没有对象,类别或帖子和类似于您已经知道的东西......

所以我的问题是:如何在类别的详细信息视图中调用此相关名称?

以下是我的模型和views.py:

class Category(models.Model):
    title = models.CharField(max_length=20)
    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("category_detail", kwargs={"slug": self.slug})


class Tag(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.title


class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    category = models.ManyToManyField(Category, related_name='posts')
    title = models.CharField(max_length=100, blank=False)
    slug = models.SlugField(unique=True)
    body = models.TextField()
    image = models.ImageField(upload_to='project/uploads/')
    tag = models.ManyToManyField(Tag, related_name='tag_post')
    date = models.DateTimeField(auto_now_add=True, auto_now=False)
    date_mod = models.DateTimeField(auto_now=True, auto_now_add=False)
    publis = models.BooleanField(default=True)

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("post_detail", kwargs={"slug": self.slug})

和views.py。

您能告诉我如何在视图中调用类别字段和相关名称吗?

class CategoryDetail(DetailView): 
    model = Category
    template_name = "cat_detail.html"


    def get_context_data(self, *args, **kwargs):
        context = super(CategoryDetail, self).get_context_data(*args, **kwargs)
        context['cat'] = get_object_or_404(Category, slug=self.kwargs.get("slug"))
        return context

1 个答案:

答案 0 :(得分:0)

一些帮助?

def get_context_data(self, *args, **kwargs):
    context = super(CategoryDetail, self).get_context_data(*args, **kwargs)
    posts = Category.objects.get(id=1).posts.all()
    for post in posts:
        post.category
    print post
    context['cat'] = get_object_or_404(Category, slug=self.kwargs.get("slug"))

    return context

我现在有了这个,但我得到的所有帖子是否属于该类别