Django: query all items that have a foreign key point to them

前端 未结 2 1876
挽巷
挽巷 2021-02-20 08:58

I have two models:

class A(models.Model):
    name = models.CharField(max_length=100, unique=True)

class B(models.Model):
    a = models.ForeignKey(A)
         


        
2条回答
  •  耶瑟儿~
    2021-02-20 09:38

    You can do it like this:

    a_qs = A.objects.filter(b = b) 
    

    where b is an object of class B and the b= refers to the lowercase model name which you want to query the reverse relationship.

    Read more on lookups that span relationships here. It covers how to do a reverse lookup on models' ForeignKey attributes

    Edit:

    If you are looking for all objects which do not have any ForeignKey objects pointing to them, you can use exclude and __isnull

    a_qs = A.objects.exclude(b__isnull = True) 
    

提交回复
热议问题