'How to set Multi Level Foreign Key field in Django?

I have a model that looks like this

# models.py
from django.db import models


class Level_0(models.Model):
    Kode = models.CharField(max_length=10, null=False, blank=False, default="")

class Level_1(models.Model):
    Kode = models.CharField(max_length=10, null=False, blank=False, default="")
    Level_0= models.ForeignKey(Level_0, on_delete=models.CASCADE)

class Level_2(models.Model):
    Kode = models.CharField(max_length=10, null=False, blank=False, default="")
    Level_1 = models.ForeignKey(Level_1, on_delete=models.CASCADE)
    # Level_0 = ????????????

    # how do I create a connection to Level_0? a field that is automatically filled with Level_0?

What I want to have is a field in Level_2 that automatically connects to Level_0 through Level_1. How do I add that field in my Level_2 model?



Solution 1:[1]

I have found the answer. I just set the default!

class Level_2(models.Model):
    Kode = models.CharField(max_length=10, null=False, blank=False, default="")
    Level_1 = models.ForeignKey(Level_1, on_delete=models.CASCADE)

    # The answer!!
    Level_0 = models.ForeignKey(Level_0, on_delete=models.CASCADE)

It connects through Level_1 and django automatically assign the value for you when you entry your data. So far this works for me.



this works if I use Django Admin, and Django automatically connects corrects it even if you fill Level_0 with something else. It will rectify it to the correct value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sutan