gpt4 book ai didi

python - Django,外键的子集

转载 作者:行者123 更新时间:2023-11-30 22:53:02 24 4
gpt4 key购买 nike

我需要一种方法来选择外键的子集,但仅限于一个子集。这是旧 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、traittype 和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

最佳答案

我打算建议你需要链接过滤器,比如

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 的建议使用 __

关于python - Django,外键的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27508669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com