Marcin Szamotulski
unread,Jan 29, 2014, 9:45:30 PM1/29/14Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Django Users, Django Developers
On 01:42 Mon 27 Jan , Marcin Szamotulski wrote:
> Hello,
>
> I have a model
>
> class Post(models.Model):
>
> ...
> authors = models.ManyToManyField('accounts.User', through='PostAuthor', related_name='authors_posts')
>
>
> class PostAuthor(models.Model):
>
> user = models.ForeignKey('accounts.User')
> post = models.ForeignKey(Post)
> ...
>
>
> How can I use the Django 1.7 Prefetch object to load PostAuthors, this
> does not work:
>
> Post.objects.prefetch_related(
> Prefetch(
> 'authors',
> queryset=PostAuthors.object.select_related('user')
> )
>
> I got an exception:
> django.core.exceptions.FieldError: Cannot resolve keyword 'authors_posts' into field. Choices are: created, id, post, post_id,
> user, user_id
>
> Thanks for help,
> Marcin Szamotulski
If somebody will search here is the solution I've found:
Post.objects.prefetch_related(
Prefetch(
'authors',
queryset=User.objects.order_by('postauthor__created'),
)
It works because when prefetching User table is joined (inner joined)
with PostAuthor table and then the order_by('postauthor__created') will
make sense since PostAuthor has a columnt 'created'.
It would be nice to have an example in the docs for that though.
Best regards,
Marcin