Retrieve list of employees in a company model in Django

I have set up the two following models:

  • Model "User"
class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField('username', max_length=30, blank=True)
    email = models.EmailField('Adresse mail', unique=True)
    first_name = models.CharField('Prénom', max_length=30, blank=True)
    last_name = models.CharField('Nom', max_length=30, blank=True)
    date_joined = models.DateTimeField('date joined', auto_now_add=True)
    company = models.OneToOneField(Customer, on_delete=models.CASCADE, blank=True, null=True)
    is_active = models.BooleanField('active', default=True)
    is_staff = models.BooleanField('staff status',default=False)
    is_superuser = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']


    class Meta:
        verbose_name = 'user'
        verbose_name_plural = 'users'

    def get_full_name(self):
        '''
        Returns the first_name plus the last_name, with a space in between.
        '''
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        '''
        Returns the short name for the user.
        '''
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        '''
        Sends an email to this User.
        '''
        send_mail(subject, message, from_email, [self.email], **kwargs)
  • Model "Customer"
class Customer(models.Model):
    name = models.CharField(max_length=200, blank=False)
    transporters = models.ManyToManyField(Transporter, blank=True)


    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Company"
        verbose_name_plural = "Companies"

I'm trying to get the list of all employees belonging to one company. I want to display this list in the django admin. My guess was to go with employees = models.ManyToManyField(User, blank=True). But it does not work because I have the following message: employees = models.ManyToManyField(User, blank=True) NameError: name 'User' is not defined.

Could you please help me with this request?

Thanks!

I will try to pull the discussion together so this question can get answered.

I think the problem here is really simple. It's just a matter of remembering that models in Django are in fact just Python programs.

You can't reference one model in another if it isn't defined yet.

Consider this really simple program:

class Foo():
  def __init__(self):
    print("hello!")

Foo()

It prints "hello!" when you run it.

Now rewrite it as:


Foo()

class Foo():
  def __init__(self):
    print("hello!")

It blows up with:

Traceback (most recent call last):
  File "/home/matt/stackmodel/test.py", line 1, in <module>
    Foo()
NameError: name 'Foo' is not defined

Much like this model. You can't reference the User model in the Customer model unless User is defined first.

(Note: this kind of confusion is a a good example of why on Stack Overflow, it can be handy to post enough of the program to get the error you are getting, rather than just the snippets you think are relevant at the time you get the error. The whole model file with the order would help here.)

Back to Top