Django-filter: filtering last entry of a kind....

Ok, to try and clarify again - because apparently what I wrote at Django-filter: filtering last entry of a kind.... - #2 by KenWhitesell is not correct.

I’m still not understanding what you’re trying to generate here. I’m trying to follow what you’ve written, but I’m not seeing where what you’re asking for is different than what was discussed at Latest database entry of a kind - #2 by KenWhitesell

You are looking for is a list of Employees, based on what criteria? (Maybe it would be better if you described how what you are looking for here is different from the previous discussion?)

Note: You cannot directly annotate a complete object.

If you want just one field from Employment, that value can be used as the annotation. If the value is the PK of that Employment, you can then use that PK in subsequent queries to retrieve the full object. Yes, it creates an N+1 query situation, which could be acceptable under certain circumstances.

Or, you could use the JSONAgg function to create a JSON representation of the portions of the Employment object that you need to prevent the N+1 situation but creating a more complex query.

Side note: One of the things you may need to realize is that not all possible queries that you may want to issue can be written in terms of Employees - at least not as a single query.

There are times when you do need to “turn a query inside out” or “sideways” to get the data you’re looking for.

If you’re using user input to select one of those types of queries, you may need to add an if condition in your view to check the value of the selected filter and execute different queries as a result of that condition.