To me it seems you are mixing the authors m2m relation and the through 
model. The 'authors' relates to User, not PostAuthor. But your queryset is 
pointing to PostAuthors.

If you want to fetch PostAuthor instances, then you should likely prefetch 
with Prefetch('postauthors', PostAuthors.objects...). I am not exactly sure 
if the 'postauthor'
lookup is right. It should be whatever post = models.ForeignKey(Post)'s 
reverse name is.

 - Anssi

On Thursday, January 30, 2014 4:45:30 AM UTC+2, Marcin Szamotulski wrote:
>
> 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 
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2af033f8-e6b3-44e3-bf35-2f62e9d5fd93%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to