Note that there are some explanatory texts on larger screens.

plurals
  1. POFilter in django: the last post of each user
    primarykey
    data
    text
    <p>I have 2 models, Author and Post , how can I make a filter who can select the last post (by id field) of each Author in one only line?, the bad approach for me is :</p> <pre><code>authors = Author.objects.all() queryset = [] for author in authors: posts = Post.objects.filter(author=author).order_by('-id') if loc: queryset.append(posts[0]) </code></pre> <p>Specifically, this is to filter my Tastypie Resource "PostResource", a filter who can give me only the last post of each user, ordered by creation </p> <h2>Complete solution with okm answer and tastypie custom filter:</h2> <pre><code>class LocationResource(ModelResource): user = fields.ForeignKey(AccountResource,'user' ) class Meta: queryset = Location.objects.all().order_by('-id') resource_name = 'location' #excludes = ['id',] list_allowed_methods = ['post','get'] authentication = ApiKeyAuthentication() authorization= Authorization() filtering = {'user': ALL_WITH_RELATIONS} def obj_create(self, bundle, **kwargs): if bundle.request.method == 'POST': return super(LocationResource, self).obj_create(bundle, user=bundle.request.user) def apply_authorization_limits(self, request, object_list): return object_list.filter(user=request.user) def dehydrate(self, bundle): return bundle def build_filters(self, filters=None): if filters is None: #if you don't pass any filters at all filters = {} orm_filters = super(LocationResource, self).build_filters(filters) if('only_lasts' in filters): query = filters['only_lasts'] sqs = Location.objects.values('user_id').annotate(max_id=models.Max('id')).values('max_id') orm_filters["pk__in"] = sqs return orm_filters </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload