Search code examples
pythondjangomany-to-many

how to query M2M with related_name


I have two really similar models with M2M field, somehow I tried to query one of them which works perfectly but when I try the same code with the other one, it gives me errors. The only difference I can find is the related_name

I found a workaround but I am still curious how can I get this to work if I met the same problem next time.

(I only wrote the M2M field I have, and each model only has one M2M field, even though come to think of it, what can be done if there are more than one M2M, but this is out of this question)

this is the working model I have

class Team(View):
    members = models.ManyToManyField(User, blank=True)

this is the view with the above model, (skipping the class, the def post and so on)

user = User.objects.filter(id=111).first()
all_members = user.Team_set.filter()  # this would return all

below is the model that is giving me problems

class Room(View):
    participants = models.ManyToManyField(User, blank=True, related_name='participants')

this is the view with the above model

user = User.objects.filter(id=111).first()
all_p = user.room_set.filter()  # this then gives me error of 'User' object has no attribute 'room_set'

Thanks in advance for any help


Solution

  • When defining related_name you need to use it like this:

    Model.related_name.* 
    

    the alias related_model_set gets destroyed.

    With that said your code should look like:

    user = User.objects.filter(id=111).first()
    all_p = user.participants.filter()  # this then gives me error of 'User' object has no attribute 'room_set'