简体   繁体   English

在Django中查询相关集合

[英]Querying related collections in Django

I'm working on a Django app that has the following layout (trimmed down and anonymized): 我正在使用具有以下布局(修剪并匿名化)的Django应用程序:

class Room(models.Model):
    pass # Bunch of fields here

class Reserveration(models.Model):
    room = models.ForeignKey(Room)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
    # more stuff

Now I'd like to do some queries that relate rooms and their collection of reservations. 现在,我想进行一些查询,这些查询与房间及其预订集合有关。 (I guess most/all of what I want to do involves selecting into a temp table...) Following are examples of the stuff I'd like to do (written in LINQ). (我想我想做的大部分/全部工作都涉及到选择一个临时表...)以下是我想做的事情(用LINQ编写)的示例。 I understand I could do these in a for loop, but I'd like to keep this in the database. 我知道我可以在for循环中完成这些操作,但是我想将其保留在数据库中。

// Return all rooms that are reserved in the future
return Rooms.Where(r => Reservations.Where(a => a.room == r)
       .OrderByDecending(a => a.end_date)
       .Single()
       .end_date > DateTime.Now);

// Return all rooms that are free right now
return Rooms.Where(r => ! Reservations.Any(a => a.room == r &&
            a.start_date < DateTime.Now && DateTime.Now < a.end_date));

I can't seem to find any information about how to preform these types of queries in Django without resorting to raw SQL. 我似乎找不到关于如何在Django中执行这些类型的查询的任何信息,而无需借助原始SQL。 Is what I'm trying even possible? 我正在尝试的可能吗?

From https://docs.djangoproject.com/en/dev/topics/db/queries/ : https://docs.djangoproject.com/en/dev/topics/db/queries/中

Use r.room_set to get the relevant queryset. 使用r.room_set获取相关的查询集。

Your first query translates to: 您的第一个查询翻译为:

r.room_set.filter(end_date__gt=datetime.date.today()).order_by('end_date')[:1]

This returns an empty set if there is no match, or a set with the first element. 如果没有匹配项,则返回一个空集合,或者返回第一个元素的集合。

The second is: 第二个是:

r.room_set.filter(start_date__lt=datetime.date.today(),
    end_date__gt=datetime.date.today())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM