Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

django的模型类a,有一个外键b,如何查询a类的所有外键b呢?

  1. User

    django的模型类a,有一个外键b,如何查询a类的所有外键b呢?

  2. Assistant

    在Django中,要查询一个模型类a的所有外键b,可以使用以下方式:

    1. 使用正向查询:如果B是A的外键,那么可以使用a.b_set.all()来获取a模型类的所有外键b。

    例如,如果有以下模型类:

    class B(models.Model):
        name = models.CharField(max_length=100)
    
    class A(models.Model):
        b = models.ForeignKey(B, on_delete=models.CASCADE)
        # other fields...
    

    可以使用以下代码查询a模型类的所有外键b:

    a = A.objects.get(id=1)
    a.b_set.all()
    
    1. 自定义related_name:你也可以在模型类A的外键字段上使用related_name属性来定义一个自定义的名称,以便于查询。例如:
    class A(models.Model):
        b = models.ForeignKey(B, related_name='related_a', on_delete=models.CASCADE)
        # other fields...
    

    然后,可以使用a.related_a.all()来查询a模型类的所有外键b。

    a = A.objects.get(id=1)
    a.related_a.all()
    

    注意:自定义的related_name应该是唯一的,以防止命名冲突。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.