我需要一种方法来选择外键的子集,但只能将其限制为子集。这是旧PHP数据库中使用的原始查询;
SELECT a.name FROM character_trait b
LEFT JOIN trait a ON b.id_trait = a.id
WHERE b.id_character = 1
AND a.id_traittype = 10
所有表格,字符,特征,特征类型和character_trait都可用,但我无法弄清楚如何在Djando中完成它。我的想法是这样的;
traits = CharacterTrait.objects.filter( id_character = character, id_trait.id_traittype = 10 )
但这只是一个错误"关键字不能成为表达式"。我可以用一种非常丑陋的方式做到这一点,并且只是迭代所产生的特征'像这样使用for循环;
traits = CharacterTrait.objects.filter( id_character = character )
for t in traits:
print t.id_trait.id_traittype.id
if t.id_trait.id_traittype.id == 10:
print "Got One"
编辑,模块定义;
class Trait(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
id_traittype = models.ForeignKey(Traittype, null=True, db_column = 'id_traittype')
name = models.CharField(max_length=32)
class Meta:
managed = False
db_table = 'trait'
def __unicode__(self):
return self.name
class Traittype(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
name = models.CharField(max_length=64)
class Meta:
managed = False
db_table = 'traittype'
def __unicode__(self):
return self.name
class Trait(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
id_traittype = models.ForeignKey(Traittype, null=True, db_column = 'id_traittype')
name = models.CharField(max_length=32)
class Meta:
managed = False
db_table = 'trait'
def __unicode__(self):
return self.name
class CharacterTrait(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
##id_character = models.IntegerField()
## id_trait = models.IntegerField()
id_character = models.ForeignKey(Werewolfcharacter, null=True, db_column = 'id_character')
id_trait = models.ForeignKey(Trait, null=True, db_column = 'id_trait')
class Meta:
managed = False
db_table = 'character_trait'
def __unicode__(self):
return self.id_trait.name
答案 0 :(得分:0)
一个简单的可能性,因为您(可能)已经在PHP代码中拥有正确的SQL,只需要use raw SQL queries in Django。
答案 1 :(得分:0)
我打算建议你需要链接过滤器,比如
traits = CharacterTrait.objects.filter( id_character = character).filter(id_trait__id_traittype = 10 )
但回头看一些代码,
traits = CharacterTrait.objects.filter( id_character = character, id_trait__id_traittype = 10 )
应该足够了,关键是要取代它。使用__,如dm03514
所示答案 2 :(得分:0)
您应该阅读lookups that span relationships上的文档。您需要使用双下划线语法:
CharacterTrait.objects.filter(id_character=character, id_trait__id_traittype=10)