Streetway Fun
Streetway Fun

Reputation: 223

Use of same related_name in a single Model. Django

I have a User model:

Class User(models.Model):
   #some fields

And another Profile Model, which consists of fields -> mother and father.

Class Profile(models.Model):
   father = models.ForeignKey(
    'User',
    related_name='children',
    on_delete = models.CASCADE)
   mother = models.ForeignKey(
    'User',
    related_name='children',
    on_delete = models.CASCADE)

Now, is it right to do so? If it is, How am I to get a User's children?

Upvotes: 4

Views: 912

Answers (2)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11705

change model to below

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
   # ....
   gender = models.ChoiceField(choices=(('m', 'Male'), ('f', 'Female')))
   # .... 

   def children(self):
       if self.gender == 'm':
          return self.fchildren
       return self.mchildren

class Profile(models.Model):
   father = models.ForeignKey(
    'User',
    related_name='fchildren',
    on_delete = models.CASCADE)
   mother = models.ForeignKey(
    'User',
    related_name='mchildren',
    on_delete = models.CASCADE)

Access the urls

 user = User.objecets.get(pk=10)
 children = user.children.all()

Upvotes: 2

Bojan Kogoj
Bojan Kogoj

Reputation: 5649

How about using a property?

class User(models.Model):
   #some fields

   @property
   def children(self):
      if self.gender == 'm':
         return self.father_children.all()
      return self.mother_children.all()

And

class Profile(models.Model):
   father = models.ForeignKey(
    'User',
    related_name='father_children',
    on_delete = models.CASCADE)
   mother = models.ForeignKey(
    'User',
    related_name='mother_children',
    on_delete = models.CASCADE)

Not ideal, but it's something

Upvotes: 3

Related Questions