[Answered ]-How to get reference table fields with django model query

1👍

This is the current implementation of my code that solved the problem.

projects = []
result = TblVersion.objects.all()    
for ver in result:
    versions.append({
        'id':ver.version_id,
        'major_version':ver.version_major,
        'minor_version':ver.version_minor,
        'project_name':ver.project.project_id,
        'project_name':ver.project.project_name,
    })

0👍

select_related method accepts an arg of fields that relates to an other model

result= TblVersion.objects.all().select_related("product")

Update

To add those related field to be serializable u can list the values as

result = TblVersion.objects.all().select_related("product").values("id", "version_id", ..., "product__id", "product__name")

0👍

You can use serializers to view the referenced table fields.

#models.py

class Product(models.Model):
    seller=models.ForeignKey(CustomUser,on_delete=models.CASCADE,null=True,blank=True)
    pname=models.CharField(max_length=100)
    category=models.CharField(max_length=100)
    description=models.TextField(null=True,blank=True)
    price=models.FloatField()

    def __str__(self) -> str:
        return self.pname
    
class Order(models.Model):
    buyer=models.ForeignKey(CustomUser,on_delete=models.CASCADE,null=True,blank=True)
    product=models.ForeignKey(Product,on_delete=models.CASCADE)
    quantity=models.IntegerField()
    totalprice=models.FloatField()

    def __str__(self) -> str:
        return self.product.pname

#serializers.py

class OrderSerializer(ModelSerializer):
    pname=serializers.CharField(source="product.pname",read_only=True)
    category=serializers.CharField(source="product.category",read_only=True)
    description=serializers.CharField(source="product.description",read_only=True)
    pprice=serializers.CharField(source="product.price",read_only=True)
    class Meta:
        model=Order
        fields=['id','buyer','product','pname','category','description','pprice','quantity','totalprice']

In serializer we’ll write fields that we want from referenced table explicitly and make it’s read_only True so that it only views in get request.
Then we include it in fields so that we can fetch it in our api.

Leave a comment