3

I have a model which is an instance for the existence of an item (a ticket), and on each creation of a ticket I create a instance of another model, a record. Each record keeps track of who made a change to the ticket, and what they did with it, it basically keeps a record of what has happened with it. I want to tickets creator and creation date to be defined as the creator and creation date of the first activity made which points to it. (The first of the many in a many to one relation.

As is, I have a function which does this very simply:

def created_by(self):
    records = Record.objects.filter(ticket=self.id).order_by('created_on')
    return records[0].created_by

However I run into an issue with this when trying to sort a collection of tickets (which is logically most often going to be sorted by creation date). I cannot sort by a function using django's filter for queries.

I don't really want to store the redundant data in the database, and I'd rather have the record than not so all date items related to the ticket can be seen in the records. Idea's on how to make it so I can sort and search by this first instance of record? (Also need to search for the creator because some users can only see their own tickets, some can see all, some can see subsets)

Thanks!

1 Answer 1

2

Assuming the Record ticket field is a Foreign key to the Ticket model:

 class Record (models.Model):
     ....
     create_time = models.DateTimeField()
     ticket = models.ForeignKey(Ticket,related_name='records')

You can replace the ModelManager (objects) of the Ticket model and override the get_queryset function:

class TicketManager(models.ModelManager):
     def get_queryset():
         return super(TicketManager, self).get_queryset().annotate(create_time=Min('records__create_time')).order_by('create_time')

class Ticket(models.Model):
     .....
     objects = TicketManager

Now every query like Ticket.objects.all() or Ticket.objects.filter(...) will be sorted by the create time

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.