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

前端 未结 2 1872
挽巷
挽巷 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条回答
  •  -上瘾入骨i
    2021-02-20 09:33

    This worked for me:

    a_qs = A.objects.filter(b__a__isnull=False).distinct()
    

    It gives only the objects of A which has a B object pointing to it. Use a__isnull=False to check whether a ForeignKey exists. If it does, it can, by definition, only point to A. Duplicates are removed with distinct().

    When a related_name parameter has been set, e.g.

    class A(models.Model):
        name = models.CharField(max_length=100, unique=True)
    
    class B(models.Model):
        a = models.ForeignKey(A, related_name='b_list')
    

    this worked:

    a_qs = A.objects.filter(b_list__a__isnull=False).distinct() 
    

提交回复
热议问题