Django ForeignKey self conditions

Viewed 54

I have the model, where each Character has 'mother' and 'father' fields. They are FroeignKey which refers to self. I want to put condition for the gender, 'F', 'Female' for the mother field and 'H', 'Male' for the father field.

class Character(models.Model):
    H = 'Male'
    F = 'Female'
    GENDER_CHOICES = (
        (H, 'Male'),
        (F, 'Female'),
    )
    
    last_name = models.fields.CharField(max_length=100)
    first_name = models.fields.CharField(max_length=100)
    gender = models.CharField(max_length=30, choices=GENDER_CHOICES, null=True, blank=True)
    mother = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='linkmother')
    father = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='linkfather')
    date_birth = models.DateField(default=date.today, null=True, blank=True)
    date_death = models.DateField(default=date.today, null=True, blank=True)

    def __str__(self):
        return f'{self.first_name} {self.last_name}'
1 Answers

You can work with the limit_choices_to=… parameter [Djangod-doc]:

class Character(models.Model):
    H = 'Male'
    F = 'Female'
    # …
    gender = models.CharField(
        max_length=30,
        choices=GENDER_CHOICES,
        null=True,
        blank=True
    )
    # …
    mother = models.ForeignKey(
        'self',
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        related_name='children_as_mother',
        limit_choices_to={'gender': F}
    )
    father = models.ForeignKey(
        'self',
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        related_name='children_as_father',
        limit_choices_to={'gender': H}
    )
    # …
Related