[Answered ]-How to create Django model field to store users related to the model?

1๐Ÿ‘

If I understand your question correctly, I think youโ€™d need your models set up like this:

class Job(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=30)
    description = models.TextField()
    pay = models.FloatField()
    category = models.CharField(max_length=3, choices=JOB_CATEGORY_CHOICES)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('jobs:detail', kwargs={
            'job_pk': self.id
          }
        )

class Applicant(models.Model):
    job = models.ForeignKey(Job, related_name="applicants")
    user = models.ForeignKey(User)

This creates a one-to-many relationship from Job to Applicant and then a one-to-many relationship from the Applicant to the User.

๐Ÿ‘คthemanatuf

1๐Ÿ‘

Assuming a user can apply to many jobs and a job can have many users applying, the simple solution is a many to many relationship, defined by a ManyToManyField:

class Job(models.Model):
    users = models.ManyToManyField(User)

Now you may want to keep track of additional informations about the application (date etc), in which case an explicit intermediate model might be handy:

class Application(models.Model):
    job = models.ForeignKey(Job)
    user = models.ForeignKey(User)
    date โผ models.DateTimeField(...)
    # etc

   class Meta:
       # you probably don't want the same user 
       # to apply twice to the same job
       unique_together = [("job", "user"),]

0๐Ÿ‘

As themanatuf said, other models with foreign keys and one to one relationships would do the trick.

I would advise you do the Django 101 polls tutorial first though โ€“ it is well explained and has very similar related-models architecture than the one you wish to build.

Have fun !

๐Ÿ‘คMalcoolm

Leave a comment