Django Multi连接查询

时间:2017-08-30 18:53:11

标签: django python-3.x django-queryset

我是django的新手,需要进行查询。我可以在sql中做,但我似乎无法在django中找到它。这是在SQL中。有人能告诉我如何在django中做到这一点。

select token from api_userprofile
join api_userdevice on api_userdevice.user_id=api_userprofile.user_id
join api_device on api_device.id=api_userdevice.device_id
where api_device.serial=3

我的模特看起来像这样:

class UserDevice(models.Model):
   user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=False)
   device = models.ForeignKey(Device, on_delete=models.PROTECT, null=False)
   activation_date = models.DateTimeField(default=timezone.now, null=False)
   friendly_name = models.CharField(max_length=20, null=True, blank=True)
   is_owner = models.BooleanField(null=False, default=False)
   is_admin = models.BooleanField(null=False, default=True)

class Device(models.Model):
    serial = models.CharField(max_length=16, null=False, unique=True)
    publickey = models.CharField(max_length=44, null=False)

class UserProfile(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, null=False)
    token = models.TextField(null=False, blank=True)

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你可以尝试:

:empty

用于检查sql查询,可以打印:

users_pks = UserDevice.objects.filter(device__serial=3).values_list('user__pk')
qs = UserProfile.objects.filter(user__pk__in=users_pks).values('token')