Django USES detail :ORM's reverse lookup of related_name

  • 2020-10-23 21:02:51
  • OfStack

First define two models, one A and one B, which are one-to-many types.


class A(models.Model):
  name= models.CharField(' The name of the ', max_length=32)

class B(models.Model):
  a= models.ForeignKey(A, verbose_name='A class ',related_name = "test")
  name = models.CharField(' call ', max_length=16)

If we want to query which B a A has, what do we do

Query the subtables through the main table


A.objects.get(id=A_id).test.all().order_by('-created'),

By default, django has one foreign key attribute for each object of the main table, which can be used to query information about all the child tables belonging to the main table. By default, the name of this property is denoted by the name of the child table in lowercase plus _set() (accessed as b_set by default above). By default, 1 querydict object is returned.

related_name can define 1 individual name for this foreign key

The primary table is queried through the child tables


B.objects.filter(a=A_id).order_by('-created')

Related articles: