How to do reverse for get_absolute_url with many t

2019-08-03 23:41发布

问题:

I have a model with many-to-many fields and I need to get an ID selected from a many to many field. I decorated a get_absolute_url method with permaling decorator. And it doesn't work. So I understand that I need to reverse the relation, it is obvious from the trace, but I do not really understand what should I do?

Model:

class MenuItems(models.Model):
    reference_value = models.CharField(max_length=255)
    filter_ids = models.ManyToManyField(Filter, blank = True)

    def __unicode__(self):
        return u'%s' % self.reference_value

    @models.permalink
    def get_absolute_url(self): 
        return ('homepage_ids', None, {'ids': self.filter_ids })

I tried to do with the reverse(), but I have the behavior of the method didn't changed.

    @models.permalink
    def get_absolute_url(self): 
        return reverse('homepage_ids', kwargs={'ids': self.filter_ids })

回答1:

without seeing the url pattern.

self.filter_ids does not return a list of ids, something like.

self.filter_ids.all().values_list('id', flat=True)

would return [1,2,3]



回答2:

You didn't post your url but something like this, should work

urls

url(r'^/something/(?P<var>\d+)/$', view_name, name="homepage_ids"),

models

@permalink
def get_absolute_url(self):
    return ('homepage_ids', [str(self.filter_ids)])

template

<a href="{{ ids.get_absolute_url }}"> {{ ids }}</a>

take a look into django tutorial



回答3:

I did it this way: url

 url(r'^(?P<ids>\d(&\d)*)?/?$', 'homepage', name='homepage'),

models

class MenuItems(models.Model):
"""Menu items... What???"""
reference_value = models.CharField(max_length=255)
filter_ids = models.ManyToManyField(Filter, blank = True, related_name="filter_ids")

def __unicode__(self):
    return u'%s' % self.reference_value

def get_absolute_url(self):
    int_ids = list(self.filter_ids.all().values_list('id', flat=True))
    str_ids = "&".join([str(val) for val in int_ids])
    return reverse('homepage', kwargs = {'ids': str_ids, })

I killed @ Permalink, because the API Permalink decorator was unuseble, convert my IDs to string with a couple of steps and apply the reverse function. The problem of the same urls of different pages are still there, but it is not important for my application, because it never will be.