can';无法访问django OneToOneField的孩子?
我试图访问OneToOneField的孩子,但我得到了错误can';无法访问django OneToOneField的孩子?,django,Django,我试图访问OneToOneField的孩子,但我得到了错误 class Products(models.Model): unique_id=models.CharField(max_length=13,unique=True) product_full_name=models.CharField(max_length=50,null=True) child_name=models.CharField(max_length=15,null=True)# name of th
class Products(models.Model):
unique_id=models.CharField(max_length=13,unique=True)
product_full_name=models.CharField(max_length=50,null=True)
child_name=models.CharField(max_length=15,null=True)# name of the model connected by OneToOneField in lowercase
def __str__(self):
return str(self.product_full_name)
def selling_price(self):
child=self.child_name
return getattr(self,child+'_set').all().first().selling_price
class Product1(models.Model):
product=models.OneToOneField(Products)
selling_price=models.FloatField()
......
class Product2(models.Model):
product=models.OneToOneField(Products)
selling_price=models.FloatField()
......
class Product3(models.Model):
product=models.OneToOneField(Products)
selling_price=models.FloatField()
......
当我尝试访问get\u selling\u price()方法时,对于连接到product1模型的Products模型,我遇到错误“Products对象没有任何属性product1\u set”。如果您的子项名称是product1,请重试
return getattr(a,child).selling_price
getattr(a,child+''u set').all().first().selling_price
这就是问题所在-逻辑是错误的那么,正确的方法应该是什么?做什么?我看不到任何的卖价,我也看不到你的目标。我根据你的错误对我所看到的进行了评论,但这种逻辑适用于其他模型。你能解释一下为什么你要获取集合的所有元素吗,如果它是一个OneToOneField?child不是一个OneToOneField是的,我知道,你应该在代码之前阅读哦,我错过了。谢谢。