19👍
✅
First, are you using a through Model? You have through in there, but you don’t have it listed. If you aren’t you don’t need it.
I would add a related_name, like so:
class Trip(models.Model):
members = models.ManyToManyField(User,blank=True,null=True, related_name='user_trips')
Then you should be able to call:
user.user_trips.all()
I called it ‘user_trips’ rather than ‘trips’ becuase if it isn’t a unique name it can cause conflicts.
If you are using a through Model, it would look more like this:
#User is defined in django.auth
class Trip(models.Model):
members = models.ManyToManyField(User,blank=True,null=True, related_name='user_trips', through='TripReservation')
class TripReservation(models.Model):
user = models.ForeignKey(User)
trip = models.ForeignKey(Trip)
registered = models.DateField()
Understand that with this way, the TripReservation refers to a particular Users reservation to the Trip, not the whole trip, and information about the trip should be properties on the Trip model itself. So, TripReservation.registered, is when that particular user registered for the trip.
The user trips lookup would be the same:
user.user_trips.all()
Source:stackexchange.com