Django:使用ManyToMany对象的绝对URL

时间:2012-03-07 02:51:34

标签: django django-urls django-orm

所以我在向Absolute URL添加ManyToMany对象时遇到问题。以下是我的模特。查看Category类。我知道我需要在URL中获得类别标题。

# Category class
class Category(models.Model):
     title = models.CharField(max_length=128)
     description = models.TextField()

     def __unicode__(self):
     return self.title


# Product class
class Product(models.Model):
    title = models.CharField(max_length=128)
    pub_date = models.DateField('date published')
    slug_title = models.SlugField(editable=False)
    cover_image = models.ImageField(upload_to="images/product/")
    image = models.ManyToManyField(Image)
    category = models.ManyToManyField(Category)
    description = models.TextField()

    def save (self):            
    self.slug_title = slugify(self.title)
    super(Product, self).save()

    def __unicode__(self):
    return self.title

def get_absolute_url(self):
    return ('product_view_url', (), {
        'category': self.category,
        'year': self.pub_date.strftime("%Y"),
        'month': self.pub_date.strftime("%m"),
        'day': self.pub_date.strftime("%d"),
        'id': self.id,
        'slug_title': self.slug_title })

get_absolute_url = models.permalink(get_absolute_url)

这是product_view_url的url.py:

    url(r'^product/(?P<category>.+)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<id>.+)/(?P<slug_title>.+)/$', index_views.product_detail, name='product_view_url'),

以下是观点:

    # Product Detail View
   def product_detail(request, id, category, slug_title, year, month, day, template='index/product_detail.html'):

   product = get_object_or_404(Product, id=id, slug_title=slug_title)

   payload = {'product': product}

   return render_to_response(template, payload, context_instance=RequestContext(request))

通过这种配置,我得到了一个奇怪的网址:'http:// localhost:8000 / product /%3Cdjango.db.models.fields.related.ManyRelatedManager%20object%20at%200x1067d6050%3E / 2012/03/07 / 1 /热带twizzler /'

我想得到这样的东西:'http:// localhost:8000 / product / candies / 2012/03/07/1 / tropical-twizzler /'

抱歉自己是个菜鸟,还在学习Django。

1 个答案:

答案 0 :(得分:1)

问题是category是ManyToManyField。根据定义,直接访问ManyToManyField不会给你一个值,而是一组值,我们称之为 ManyRelatedManager 。为了从经理实例中挑出一个值,您应该能够找出here