class Category(models.Model):
    '''Category for men's and women's items'''
    gender = models.IntegerField(choices=[
        (1, 'Women'),
        (2, 'Men'),
    ], default=1)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=300, blank=True)
    uploaded_date = models.DateTimeField(
        auto_now_add=True, null=True, blank=True)

    class Meta():
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.get_gender_display() + ' ' +

    def get_absolute_url(self):
        if # condition: more than 1 value passed from url
            return reverse('boutique:category', kwargs={'gender': self.get_gender_display(), 'category_pk':})
            return reverse('boutique:show-all', kwargs={'gender': self.get_gender_display()})

Question: how to work out the logic for get_absolute_url function to work more dynamically? Or is it not supposed to work dynamically? In the if statement above, I want to place a condition which checks how many values passed from url, so that it can decide which view to render. Is it possible? or should I just create get_FOO_url() function separately for rendering each view with different values passing in from url?

  • 呐爱
    呐爱 回复


    I personally prefer it was designed for exactly that purpose.

    from django_global_request.middleware import get_request
    class TestModel(models.Model):
        def get_absolute_url(self):
            request = get_request()
            if request.GET.get('whatever'):
                return ...
                return ...