Home > Enterprise >  How can I get list of rooms user joined via another model
How can I get list of rooms user joined via another model

Time:10-28

I have 3 models: User, Room, Join. I'm trying to get a list of room user has joined but I don't know how.

# models.py
class User(models.Model):
  full_name = models.CharField(max_length=40)

class Room(models.Model):
  room_name = models.CharField(max_length=40)
  create_by = models.ForeignKey(User, on_delete=models.CASCADE)

class Join(models.Model):
  room = models.ForeignKey(Room, on_delete=models.CASCADE)
  user = models.ForeignKey(User, on_delete=models.CASCADE)

I tried using related_name and related_query_name but unfortunately I don't know how these things work. If my question is duplicated, please provide me some keywords, thank you in advance.

CodePudding user response:

You can obtain the Rooms for which a Join with myuser exists with:

Room.objects.filter(join__user=myuser)

If it is possible that the same User has joined the same Room multiple times, you can work with:

Room.objects.filter(join__user=myuser).distinct()
  • Related