我有Django模型:
class Species(models.Model):
species_id = models.IntegerField(db_column='Species ID', primary_key=True)
name = models.CharField(db_column='Name', max_length=100)
class Status(models.Model):
species_id = models.ForeignKey(Species, db_column='Species ID', primary_key=True)
protected = models.NullBooleanField(db_column='Protected')
class Images(models.Model):
species_id = models.ForeignKey('Species', db_column='Species ID')
url = models.CharField(db_column='URL', max_length=719)
有没有办法在不使用原始SQL的情况下执行以下SQL查询。
SELECT Name, URL FROM Images i
INNER JOIN Species s USING (`Species ID`)
INNER JOIN Status st USING (`Species ID`)
WHERE `st`.`Protected` = TRUE
答案 0 :(得分:1)
这就是我重构代码的方式:
class Species(models.Model):
name = models.CharField(db_column='Name', max_length=100)
class Status(models.Model):
species = models.ForeignKey(Species, db_column='Species ID', primary_key=True)
protected = models.NullBooleanField(db_column='Protected')
class Images(models.Model):
species = models.ForeignKey('Species', db_column='Species ID')
url = models.CharField(db_column='URL', max_length=719)
然后我会这样做:
protected_species = Status.objects
.filter(protected=True)
.values_list('species_id', flat=True)
Images.objects.filter(species_id__in=protected_species)
.values('url','species__name')
但正如@Maxime Lorant所说,我觉得你的模特很眩目。
答案 1 :(得分:0)
如果您稍微更改模型,可以执行以下操作:
images = Images.objects.filter(species__status__protected=True)
更新模型:
class Species(models.Model):
name = models.CharField(max_length=100)
class Status(models.Model):
species = models.ForeignKey('Species', primary_key=True)
protected = models.NullBooleanField()
class Images(models.Model):
species = models.ForeignKey('Species')
url = models.CharField(max_length=719)
答案 2 :(得分:0)
您的数据库结构首先是破碎的。我想每个Species
对象只有一个状态,所以你不需要有3个模型。有2个型号,您可以执行以下操作:
class Species(models.Model):
species_id = models.IntegerField(db_column='Species ID', primary_key=True)
name = models.CharField(db_column='Name', max_length=100)
protected = models.NullBooleanField(db_column='Protected')
class Images(models.Model):
species = models.ForeignKey('Species', db_column='Species ID')
url = models.CharField(db_column='URL', max_length=719)
# query
data = Images.objects.filter(species__protected=True).values('url', 'species__name')