I have a profile.
class UserProfile(models.Model):
user = models.ForeignKey(User, related_name="%(class)s", unique=True)
providers = models.ManyToManyField(ServiceProvider, related_name="%(class)s")
class ServiceProvider(models.Model):
name = models.CharField(max_length=200, null=False, default="ims")
How do I get to the user object with just having the profile object.
Can I do: (assuming I have my service provider object)
provider.userprofile.user.get() // or something like that.
I’d like to do that in one sql query. So if I had just the pk of the provider, it would be great to get to the user profile and/or the user that holds that provider.
Since your User is just a foreign key, all you need is
provider.userprofile.userIf you don’t want that to incur a second SQL query, you can just use the
select_relatedoption when selecting your profile, like:As written, your models don’t provide a trivial way to get from the provider to the User, since there is a ManyToMany from the
ServiceProviderto theUserProfile. You’ll have to get the set ofUserProfiles associated with the provider, get the one you want, and then proceed to get the User as above.