【问题标题】:How to Access Child Model data from Parent model in django如何在 django 中从父模型访问子模型数据
【发布时间】:2020-06-06 15:17:55
【问题描述】:

我有这些模型

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

【问题讨论】:

    标签: python mysql django django-orm


    【解决方案1】:

    你可以通过Django自动建立的反向关系获得Product_features,并以正向关系的related_name命名。

    因此,您可以获得Product_feature 对象中的QuerySet

    myproduct<b>.product_feature.all()</b>

    话虽如此,通常ForeignKey 字段的相关名称应该是复数,因为它是一个集合。因此,我建议将您的 related_name='product_feature' 重命名为 related_name='product_features'

    另外根据PEP-8,类名写在CamelCase,所以ProductFeature,不是Product_feature

    【讨论】:

    • 不工作它显示错误'ReverseManyToOneDescriptor'对象没有属性'all'
    • @SahilShiakh:那么你的myproduct 不是 Product 对象,而是产品
    • 我不明白你想说什么,因为我是 Django 新手,请检查我的模型并提出任何更改建议?
    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多