Reputation: 2011
I am new to Django and I am trying to get a list of meetings that a user is in, so that I can display them on a calendar. I have the following in models.py
:
class CustomUser(AbstractUser):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200, null=True)
email = models.EmailField(max_length=70, null=True, unique=True)
password = models.CharField(max_length=50, null=True)
class Meeting(models.Model):
id = models.AutoField(primary_key=True)
admin = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
name = models.CharField(max_length=20, null=True)
location = models.CharField(max_length=200, null=True)
start_date = models.DateTimeField(default=None, null=True)
end_date = models.DateTimeField(default=None, null=True)
description = models.CharField(max_length=2000, null=True)
class Member(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE)
Essentially, a user and a meeting are linked in the Member model. I have the following function in database.py
, which creates a new Meeting:
def createMeeting(name, location, admin, start_date, end_date, description):
new = Meeting(name=name, location=location, admin=admin, start_date=start_date, end_date=end_date, description=description)
if not duplicate(Meeting, new):
new.save()
membership = Member(user=admin, meeting=new)
if not duplicate(Member, membership):
membership.save()
For a certain user that is logged in, I want to be able to get a list of all the meetings that they are a member of. I know that I will need to use the Member model, but I am not sure what is the best method to get all the meetings a user is in. Any insights are appreciated.
Upvotes: 1
Views: 99
Reputation: 477318
You can filter your meetings with:
Meeting.objects.filter(member__user=request.user)
This will return all Meeting
s for which there exists a related Member
object with as user
the request.user
.
Upvotes: 2