如何使用外键过滤表中的数据?

时间:2016-02-22 18:30:46

标签: python django django-models

我有以下型号:

#- coding: utf-8 -#

STATUSES = (
    (u'R', u'Solicitada'),           # Request
    (u'V', u'Válida'),               # Deposit
    (u'P', u'Imprimiendo'),          # Printing
    (u'S', u'Por Entregar'),         # Stock
    (u'D', u'Entregada'),            # Delivered
    (u'F', u'Olvidadas')             # Forget
)

class Order(models.Model):
    requester = models.CharField(max_length=128)

class OrderStatus(models.Model):
    order = models.ForeignKey(Order, related_name="statuses")
    status = models.CharField(max_length=1,choices=STATUSES)
    date = models.DateTimeField()

我需要按状态和日期过滤订单。我尝试过以下方法:

orders_sold = Order.objects.all()
orders_sold = orders_sold.filter(statuses__status='V')

但它会返回它想要的任何东西,并且在日期之前,我已经尝试过:

orders_sold = orders_sold.filter(statuses__date__range=[from_date,to_date])

但它说'" date"不存在。

我如何实现我的目标?

更新

错误" date"给出的是:

Cannot resolve keyword 'date' into field. Choices are: added, additionalinfoorder, email, id, orderitems, password, payment, payment_date, payments, phone, print_orders, requester, statuses, taker, viewed

2 个答案:

答案 0 :(得分:0)

blog post;查询反向查找并不是Django的支持功能。你必须采取不同的方法。这是一个想法 -

order_with_status_v = OrderStatus.objects.filter(status='V',date__range=[from_date,to_date]).values('order')

现在,需要注意的是.values()从SQL关系中收集值并将其存储在字典中;存储外键的ID,但丢失其他信息。因此,您要访问的任何信息都必须列在values

的参数中
.values('order', 'order__requester')

为了在很少的2分贝命中中执行此操作,请尝试以下操作:

# list of the PK of all orders referenced by any OrderStatus with status "V"
order_statuses_v = OrderStatus.objects.filter(status='V',date__range=[from_date,to_date]).values_list('order__pk',flat=True)
# All orders referenced by OrderStatus with status "V"
orders_sold = Order.objects.filter(pk__in=order_statuses_v)

答案 1 :(得分:0)

首先,您的date字段似乎是空的。您可以在首次创建OrderStatus对象时保存日期:

date = models.DateTimeField(auto_now_add=True)

现在你有一个date,你可以按status date进行过滤:

orders_sold = Order.objects.filter(statuses__status='V', statuses__date__range=(from_date,to_date))