[英]How to Access Child Model data from Parent model in django
我有这些模型
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=255, null = False, unique=True)
product_title = models.CharField(max_length=255, null = True)
product_price = models.CharField(max_length = 255)
brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True)
product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
class Feature(models.Model):
feature_id = models.AutoField(primary_key=True)
feature_name = models.CharField(max_length=255, null = False)
product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
feature_has_value = models.CharField(choices=has_value_choice, max_length = 1, null = False)
class Product_feature(models.Model):
product_feature_id = models.AutoField(primary_key=True)
feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name='product_feature')
product_feature_value = models.CharField(max_length=255, null = False)
现在,如何从产品模型中获取 product_features ? 我想这样查询
SELECT p.*, f.* from product p, product_feature f where f.product_id = p.product_id ORDER BY P.product_type_id
您可以通过 Django 自动生成的反向关系获取Product_feature
,并以正向关系的related_name
命名。
因此,您可以通过以下方式获得Product_feature
对象的QuerySet
:
myproduct.product_feature.all()
话虽如此,通常ForeignKey
字段的相关名称应该是复数,因为它是一个集合。 因此,我建议将您的related_name='product_feature'
重命名为related_name='product_features'
。
此外,根据PEP-8 ,类名是用CamelCase
写的,所以ProductFeature
,而不是 。Product_feature
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.