简体   繁体   中英

How to Access Child Model data from Parent model in django

I have these models

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)

Now, how can I fetch product_features from product model? I want to query like this

SELECT p.*, f.* from product p, product_feature f where f.product_id = p.product_id ORDER BY P.product_type_id

You can obtain the Product_feature s by the reverse relation that Django automatically makes, and is named after the related_name of the forward relation.

You thus can obtain a QuerySet of Product_feature objects with:

myproduct

That being said, normally the related name of a ForeignKey field should be plural , since it is a collection. I therefore advise to rename your related_name='product_feature' to related_name='product_features' .

Furthermore according to PEP-8 , a class name is written in CamelCase , so ProductFeature , not Product_feature .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM