Django仅在其中一个子对象满足条件的情况下获取对象

时间:2019-10-19 11:54:42

标签: python django

所以我有两个模型:

class Business(models.Model):
    def __str__(self):
        return self.name

    name = models.CharField(max_length=200)

class Appointment(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name="appointments")

在我看来,我具有以下背景:

def home(request):
    [...]
    context = {
        'business':Business.objects.order_by('name'),
    }
    [...]

现在,我将使用其子模型“ Appointment”来获得所有企业。

但是我只想要在现有子模型中“填充”完全满足author == request.author

的企业

另外,业务的子模型“约会”应仅是其作者​​等于request.author的“约会”

1 个答案:

答案 0 :(得分:1)

我们可以做这样的事情:

business = Business.objects.filter(appointment__author=request.author)

或者:

business = Business.objects.filter(appointment__author__id=request.author.id)

您可能需要阅读:Lookups that span relationships