2012-03-07 41 views
0

所以我在将一个ManyToMany对象添加到我的绝对URL时遇到了问题。以下是我的模特。查看Category类。我知道我需要将类别标题放入网址中。Django:使用ManyToMany对象的绝对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)) 

有了这个配置,我得到一个奇怪的URL:“HTTP://本地主机: 8000/product /%3Cdjango.db.models.fields.related.ManyRelatedManager%20object%20at%200x1067d6050%3E/2012/03/07/1/tropical-twizzler /'

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

对不起,作为一个noob,仍在学习我的方式在Django周围。

+0

你可以发布你的urls.py吗?我需要看看你如何定义'product_view_url''。 – tamakisquare 2012-03-07 03:09:41

+0

@ahmoo我更新了帖子。 – Infinixd 2012-03-07 03:15:42

回答

1

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