'RelatedManager' object has no attribute

Django

Django Problem Overview


I have a model defined like this:

class UserDetail(models.Model):
    user = models.ForeignKey(User, db_index=True, unique=True, related_name='details')
    favourites = models.ManyToManyField(Article, related_name='favourited_by', blank=True)

And I'm trying to do something like this:

article = get_object_or_404(Article, pk=id)
request.user.details.favourites.add(article)

Why isn't it working?

I'm getting this error:

> 'RelatedManager' object has no attribute 'favourites'

I guess details isn't the right type, but why isn't it? And how can I perform a query like that?

Django Solutions


Solution 1 - Django

When you access user.details, it accesses the backreference of the UserDetail.user foreign key. The foreign Key itself doesn't specify that a User can only have one UserDetail, so django gives you a RelatedManager, which you can filter and query just like a regular Manager. So you do the same things to it that you do to your .objects managers. You can ask for user.details.all(), user.details.filter(), user.details.get(), and so on, which will either give you a queryset, an object, or an exception,depending on the method and the results.

Solution 2 - Django

Try

request.user.details.get().favourites.add(article)

This assumes the UserDetail object already exists for that user, otherwise get() will raise an exception.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmpenView Question on Stackoverflow
Solution 1 - DjangojcdyerView Answer on Stackoverflow
Solution 2 - DjangoAlasdairView Answer on Stackoverflow