在渲染详细信息视图时从对象获取pk的外键

时间:2017-06-29 17:03:56

标签: django django-views django-class-based-views

我试图获取外键关系的id来执行以过滤模型列表。但是我得到的错误表明:' ForwardManyToOneDescriptor'对象没有属性' id'。这是解决这个问题的正确方法,还是我在理解这一切是如何工作的时候遗漏了一些东西?

我从这个模型创建了一个详细视图:

class Collection(models.Model):
  title = models.CharField(max_length=32, null=True)
  slug = models.SlugField(unique=True, blank=True)
  category = models.ForeignKey(Category)

  @models.permalink
  def get_absolute_url(self):
    return ('collection_detail', (),
            {
                'slug' :self.slug,
            })


  def __unicode__(self):
    return u'%s %s  ' % (self.category.id, self.title
                               )

这是详细视图中的代码:

class collection_detail(DetailView):
   model = Collection

def get_context_data(self, **kwargs):
    context = super(collection_detail, self).get_context_data(**kwargs)
    a = self.category.id
    context['collection_list'] = Product.objects.filter(categories=a).order_by('id')
    return context

1 个答案:

答案 0 :(得分:1)

self.category.id更改为self.object.category.id

The documentation州:

  

在执行此视图时,self.object将包含视图正在操作的对象。