如何创建一个函数来检查单独模型中另一个字段的属性?


class Trait(models.Model):
name = models.CharField(max_length=20)
animal_types = models.ManyToManyField(AnimalType)
# slots = models.CharField(default=None, null=True, max_length=4)
#slots is meant to hold a value that determines where it can be placed in animal model
#i.e. null means anywhere, "2" means only trait 2
#def TraitPlace(self):
def __str__(self):
return self.name
#need to add animal details like age and gender to a separate model or integrate/hardcode into animal model as they're only 7 options
class ANIMAL(models.Model):
animal_type = models.ForeignKey(AnimalType, on_delete = models.CASCADE)
first_trait = models.ForeignKey(Trait, on_delete = models.CASCADE)
#first trait and animal required as animals always exist and have at least one trait
#  second_trait= models.ForeignKey(Trait, on_delete = models.CASCADE)
# third_trait= models.ForeignKey(Trait, on_delete=models.CASCADE)

我有一个动物模型,用来创建一个动物多达3个特征,问题是一些特征有特定的放置限制,即"只能在3号位置,闪光只能在2号和3号位置。有人建议增加额外的"插槽"。属性。

我理解逻辑上它应该如何工作,但我正在努力实现。我试着在我的first_trait下查找文档和使用hasattr,但那不起作用,或者我只是没有正确的位置。从本质上讲,我想让它这样做,当动物模型被调用时,一个人添加了第二个特征,让它去检查"槽";属性在数据库中查看该"性状"的位置。是有效的。如果slot是1,2;或者"2,3",他们将分别被限制在第一和第二,第二和第三的位置。我花了很多时间试图让这个工作,但无法做到,希望你们中的一个网络传奇可以帮助我或指出我正确的方向。谢谢。

你可能想尝试添加一个模型类来验证数据之前插入/更新到动物&特征

class AnimalTraits(models.Model):
trait_name = models.ForeignKey(Trait)
animal_type = models.ForeignKey(ANIMAL)
slots = models.CharField(default=None, null=True, max_length=4)

一个sql查询找出哪些槽是有效的一些用户输入动物&Trait应该是这样的

SELECT at.slots from AnimalTrait at, ANIMAL a, Trait t 
WHERE at.animal_type = a.animal_type
AND at.trait_name = t.name
AND a.animal_type = `$user_input_animal_type`
AND t.name = `$user_input_trait`;

,您可以添加一些业务逻辑来确定用户输入槽是否在该返回值中。好的是,这也可以用来确定该特征是否对动物有效

相关内容

最新更新