newprogrammer12
newprogrammer12

Reputation: 243

OnetoMany field in django models

From my search it comes to my understanding there is no OnetoMany Field in django, can someone explain or simplify a solution if i wanted to have these three classes connected to each other.

a UserRank class which i can define as many as ranks i want,example (captain,2nd eng,chief mate...etc) a User class which can have one of the above ranks, a job class which can have 1 or many ranks from the UserRank class

models.py

class UserRank(models.Model):
    rank = models.CharField(blank=True,null=True,max_length=150)
   

    def __str__(self):
        return self.rank


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=150,unique=True)
    name = models.CharField(max_length=150,)
    phone = models.CharField(max_length=50)
    date_of_birth = models.DateField(blank=True, null=True)
    picture = models.ImageField(blank=True, null=True, upload_to='users_imgs')
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)
    last_login = models.DateTimeField(null=True)
    user_rank = models.ForeignKey(UserRank,related_name='userRank',null=True,on_delete=models.SET_NULL)
    objects = UserManager()

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

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username.split()[0]

class Job(models.Model):
    job_type = (
        ('I', 'Interval'),
        ('O', 'One time'),
    )
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    type = models.CharField(max_length=1, choices=job_type)
    interval = models.IntegerField()
    is_critical = models.BooleanField()
    due_date = models.DateField()
    user_rank = models.ManyToManyField(UserRank,related_name='ranks',blank=True)
    component = models.ForeignKey(
        Component, related_name='jobs', on_delete=models.CASCADE)
    runninghours = models.ForeignKey(
        RunningHours, related_name="RHjobs", on_delete=models.CASCADE)   

    def __str__(self):
        return self.name

Upvotes: 0

Views: 607

Answers (2)

Beikeni
Beikeni

Reputation: 900

In a one-to-many relationship, the "child" instance contains the primary key of the parent instance as a foreign key.

This means that if you have a relationship between UserRank and Job, each Job instance will have an attribute of type ForeignKey containing the primary key of the parent Job instance.

# Setup 
class UserRank(models.Model):
    ...attributes

class Job(models.Model):
    user_rank = models.ForeignKey(UserRank, on_delete=models.CASCADE, related_name="jobs")

# Accessing jobs from UserRank
user_rank_1 = UserRank.objects.create(...)

# There is one UserRank instance with many child job instances, so we have to cycle through them
for job in user_rank_1.jobs.all():
   print(job)

# Result
# >>> job1
# >>> job2
# >>> job3

# Accessing UserRank from a Job instance
job = Job.objects.get(id=1)

# Every job instance only has one parent UserRank, so it's sufficient to reference it directly with the dot notation
print(job.user_rank)

# Result
# >>> user_rank_1


Upvotes: 1

nigel222
nigel222

Reputation: 8202

You are probably looking for the "reverse relation" of a ForeignKey relation. Look at the Django documentation: Following relationships backwards

(Summary: Entry has a foreign key to Blog, and by default Blog.entry_set is a manager for related Entry objects, f.ex. Blog.entry_set.all() or any more complex Queryset to filter them. THe name entry_set is a default, you can change it via related_name on the ForeignKey in Entry)

Upvotes: 1

Related Questions