[Django]-Django equivalent of Rail's has_one through

2👍

This should do what you want:

from django.contrib.auth.models import User
from django.db import models


class Company(models.Model):
    name = models.CharField()
    users = models.ManyToManyField(User, through='CompanyMember')

class CompanyMember(models.Model):
    company = models.ForeignKey(Company)
    user = models.ForeignKey(User, unique=True)

More info: https://docs.djangoproject.com/en/1.7/topics/db/models/#extra-fields-on-many-to-many-relationships

Update:

To access the company for a given user, you can now do this:

myuser.company_set.first()

You probably don’t want to change the built-in User model. But you can add your own convenience methods/properties fairly easily by using a proxy model, ex:

class MyUser(User):
    @property
    def company(self):
        return self.company_set.first()
    class Meta:
        proxy=True

Then, any time you would normally use a User object, use MyUser instead and it will have that convenience property for you. Ex:

MyUser.objects.get(id=123)

will be the same record as

User.objects.get(id=123)

but you’ll have the extra convenience methods/properties on the object. Ex:

myuser = MyUser.objects.get(id=123)
myuser.company
👤dylrei

Leave a comment