Django orm self from the association table

Self-association model

Self-association model is a column of the table, this table associated with another one. The most typical self-association model is the regional table. Provincial cities and counties are in a table inside. pid pid province is null, the provincial city of pid pid, the county is the city of ID.

class Area (models.Model): 
    name = models.CharField (= max_length 20, verbose_name = " name " ) 
    parent = models.ForeignKey ( " Self " , verbose_name = " superior administrative division " ) 

    class Meta: 
        db_table = " db " 
        verbose_name = " administrative division "

Inquired how that

If you know a city to pay a city, I want to check it belongs to what province

a = Area.objects.get(id=1)

# B is a city of the identity object

b = a.parent

If you know of a province, called a province, he check with what City

# B is the whole city of a province of the object

b = a.area_set.all () # lowercase class name + "set"

Guess you like

Origin www.cnblogs.com/tangda/p/12090669.html