[Answer]-Django: Two ManyToManyField to the same model

1πŸ‘

I have tried 'user.question_set.all()', but it doesn’t work

As you are using a custom auth model, you should use get_user_model() to fetch the model that the authentication framework is using:

from django.contrib.auth import get_user_model

user_model = get_user_model()

To fetch the questions for a particular user:

user_model = get_user_model()
user = user_model.objects.get(pk=1)  # Now this is not the "normal" User

user_questions = Question.objects.filter(author=user)
user_favorites = Question.objects.filter(favorite_users=user)
πŸ‘€Burhan Khalid

0πŸ‘

To get all questions asked by a certain user, use Question.objects.filter(author=user). Similarly, to get all questions favorited by a certain user, use Question.objects.filter(favourite_users=user).

The documentation contains some very helpful examples of lookups across many-to-many relationships.

Leave a comment