Django-models.py-get_absolute_url函数是否带条件?

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() + ' ' + self.name

    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': self.pk})
        else:  
            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 https://pypi.org/project/django-middleware-global-request/ 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 ...
            else:
                return ...
    
    

    您只需要确保,仍然可以在没有任何可用请求的情况下访问此方法。因此,请确保它是失败保存的,并且在没有请求的情况下具有后备功能(例如在shell中,在升级中等)