Wednesday, January 29, 2014

Re: Prefetch object (django 1.7)

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+unsubscribe@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/20140130024431.GK31583%40flying-circus.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment