Home > database >  How can make foreignKey from the same table in django?
How can make foreignKey from the same table in django?

Time:05-18

How can make foreign-key from the same table in Django admin?

For example, I have data of persons with first name and last name:

  1. Joe Ni
  2. Joe Ri
  3. Bob Gh

and I have a Person model:

class Person(models.Model):
   name = models.CharField(max_length=25)
   lname = models.CharField(max_length=25, blank=False)

   def __str__(self):
        return str(self.name)


class MyModel(models.Model):
    first_name = models.ForeignKey(Person, on_delete=models.CASCADE)
    last_name = models.ForeignKey(Person, on_delete=models.CASCADE)

Now i wanna choose for example the value 'Joe' in "MyModel" and then it will show me all the other valid options for this first name: NI, RI

How can i do it?

TNX guys

CodePudding user response:

To correctly map the described relation between first name and last name I would propose something like this.

class FirstName(models.Model):
    value = CharField(max_length=25)  

class LastName(models.Model):
    first_name = models.ForeignKey(FirstName, on_delete=models.CASCADE)
    value = CharField(max_length=25)
   

You will then some JavaScript in your form to make sure the list of available last names for a given first name is dynamically updated.

  • Related