渲染细节视图时从对象获取外键的pk

Get pk of foreign key from object when rendering detail view

我正在尝试获取外键关系的 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

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

The documentation 状态:

While this view is executing, self.object will contain the object that the view is operating upon.