简体   繁体   中英

Create a list of objects with unique FK and most recent timestamp using Django

I want to create a list of Task objects that is the most recent task record for every client. Then use this list to create a list of dictionaries (specifying the client, some task_values, and date) for each object in the task list. I have a model that looks like this:

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

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

class Task_Type(models.Model):
    name = models.CharField(
                        max_length = namelen,
                        unique = True,
                        )

class Task_Value(models.Model):
    value_char = models.TextField
    task = models.ForeignKey('Task',)
    field = models.ForeignKey('Task_Field')  

My attempt at this looked something like this:

task_objs=Task.objects.filter(client__in=client_list, task_type=1).distinct().order_by('-timestamp')
task_dict = [{task_obj[x].client.pk:task_obj[x].task_value_set.get(field__name__exact='ABC').value_char} for x in range (0,len(client_list),1)]  

But this gives me distinct records for every client and timestamp combination (so all records). So two questions, how do I get a distinct record for each client that is the most recent record for the client? and two, is there a better method overall than what I described for getting the task_dict?

See this question . I suggest the first answer, the custom method (2nd answer) will add a lot of load to the DB for large querysets.

Using AgDude's suggestion for spanning relationships with values. I move my query back one step and am querying the Tasxk_Value model, filtering Tasks by spanning the relationship in the filter command. Then spanning relationships with the values_list.

If one does the following: queryset.value_list('pk', 'task__timestamp'), another queryset.values_list('pk', 'task__client'), and another queryset.values_list('pk','value_char'). Then using dict(), each of the values lists are transformed into dictionaries that can be used to parse the desired values out.

In cases where just the most recent client and value_char are desired, a single values_list('task__client', 'value_char') and dict() are all that is required. However the queryset needs to be ordered from oldest to newest as the iterations writes over previously stored values.

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