我有两个Django模型:
class Animals(models.Model):
id = models.AutoField(primary_key=True)
name = models.TextField(unique=True)
class Meta:
db_table = 'animals'
class AnimalSounds(models.Model):
id = models.AutoField(primary_key=True)
animal = models.ForeignKey(Animal, on_delete=models.PROTECT)
sound = models.TextField(unique=True)
class Meta:
db_table = 'animal_sounds'
现在我的SQL查询看起来像这样:
SELECT * FROM animals WHERE animals.id IN (
SELECT animal_id FROM animal_sounds
)
我将如何使用 Django 模型来做到这一点?概念上是这样的:
Animals.objects.filter(id__in=AnimalSounds.objects.all('ids'))
您可以检查是否至少有一个AnimalSound
与以下内容相关:
Animal.objects.filter(animalsounds__isnull=False).distinct()
这将执行如下查询:
SELECT DISTINCT animal.*
FROM animal AS ani
JOIN animalsounds AS ans ON ans.animal_id = ani.id
或者,您可以将您的方法用于:
Animals.objects.filter(
id__in=AnimalSounds.objects.values('animal_id', flat=True)
)
但我更喜欢前者,因为它更具声明性且更短。
编辑:如果要选择具有相关AnimalSounds
对象的所有Animal
,其中sound
'woof'
,可以这样写:
# animals that produce woof (and perhaps other sounds)
Animal.objects.filter(animalsounds__sound='woof').distinct()