编程语言
首页 > 编程语言> > python-外键Django管理员的日期范围列表过滤器

python-外键Django管理员的日期范围列表过滤器

作者:互联网

我有这样的模特

class BaseRequest(models.Model):
    created = models.DateTimeField(auto_now_add=True, editable=False)
    modified = models.DateTimeField(auto_now=True, editable=False)   
    price_quoted =  models.DecimalField(max_digits=10, decimal_places=2,null=True, blank=True)

 class RequestLeg(models.Model):
    created = models.DateTimeField(auto_now_add=True, editable=False)
    modified = models.DateTimeField(auto_now=True, editable=False)
    depart_date = models.DateField()
    num_seats = models.IntegerField()

class Request(BaseRequest):
    owner = models.ForeignKey(User, null=True, blank=True)
    name = models.CharField(max_length=30, null=True, blank=True)
    email = models.EmailField()
    phone = models.CharField(max_length=30, null=True, blank=True)
    legs = models.ManyToManyField(RequestLeg)

和上述请求模型的管理员是

class RequestAdmin(NoDeletionsAdmin):
    list_display=['id', 'created', 'name', 'depart_date']

    def depart_date(self, obj):
        try:
            return min([leg.depart_date for leg in obj.legs.all()])
        except ValueError, e:
            return None

我想在RequestAdmin中使用depart_date的Daterangelist过滤器?

解决方法:

就像任何其他关系一样,使用field lookups对其进行过滤:

Request.objects.filter(legs__created__range=["2015-01-01", "2016-01-31"])

如果需要从父模型中筛选字段,建议阅读Multi-table inheritance.

一个TL; DR就是Django在子模型上隐式创建一个OneToOneField,我们可以像过滤其他任何字段一样对其进行过滤,例如:

BaseRequest.objects.filter(request__depart_date__range=[...])

要么

Request.objects.filter(baserequest_ptr__created__range=[...])

但是,通常最好这样编写第二个查询,让Django处理内部信息:

Request.objects.filter(created__range=[...])

标签:django-admin,python,django
来源: https://codeday.me/bug/20191028/1949630.html