简体   繁体   中英

How do I filter by a date range based on a dictionary value in python, otherwise filter a list by a dictionary?

I have a dictionaries that look like this:

s_dates_dict = {17: datetime.date(2009,21,9,0,24), 19: datetime.datetime(2011,12,1,19,39,16), ....}  
e_dates_dict = {17: datetime.date(2010,25,9,10,24), 19: datetime.datetime(2012,1,11,17,39,16), ....}

I want to use these dictionaries to find the next record of type (A or B) after that date for each record. So it seems that I would be best off creating a query similar to below:

next_record_list = Tasks.objects.filter(date__range(s_dates_dict,e_dates_dict), client__in=client_list, task_type__in=[A,B])  

Whereby the dictionaries would cause a dynamically changing range to the pk referenced. I haven't found anything suggesting this is possible or efficient, so I am guessing the next best would be creating a list by eliminating the date range filter and then iterating a dictionary of the oldest values using a for statement and cutting off iteration of each record at the date referenced in dates_dict. But I haven't figured out a method to do this either. Could I get some suggestions of how to do this, or a totally different better method? Thanks.

EDIT:

client_list is a list of client objects.

Here is some of the models.py:

class Client(models.Model):
    user_name = models.CharField

class Task(models.Model):
    client = models.ForeignKey(
                               'Client',
                               )
    task_type = models.ForeginKey(
                                  'Task_Type',
                                  )
    date = models.DateTimeField(
                                 default = datetime.now(),
                                 blank = True,
                                 null = True,
                                 )

class Task_Type(models.Model):
    name = models.CharField  

I think I understand now. I am assuming client_list is actually a list of client objects. Someone may come up with a more efficient solution, but I would try something like this:

next_record = {}
for client in client_list:
    s = s_dates_dict[client.pk]
    e = e_dates_dict[client.pk]
    next_record[client.pk] = client.tasks_set.filter(date__range(s,e), task_type__in=[A,B])

This gives you a dict ( next_record ) where each key corresponds to a list of tasks. I am assuming there is a ForeignKey relationship between your Tasks and Client models.

Hopefully this works, if not, can you please post the code for your models?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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