I keep struggling with Django Model, Managers' relations.
I have a Profile model, Product Model, and Holding model.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
products = models.ManyToManyField(Product, blank=True, through='Holding')
def __str__(self):
return str(self.user)
class Product(models.Model):
product_name = models.CharField(max_length=255, blank=False, unique=True)
product_slug = models.CharField(max_length=50, blank=True,null=True)
product_symbol = models.CharField(max_length=50, blank=True,null=True)
product_price = models.FloatField(blank=True,null=True)
def __str__(self):
return str(self.product_name)
class Holding(models.Model):
product_name = models.ForeignKey(Product, on_delete=models.CASCADE)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
product_holding = models.FloatField(max_length=50, blank=True, null=True)
def __str__(self):
return str(self.product_name)
I'm trying to retrieve the data from a user (Profile)
for a Product within Holding
Basically I want to show the amount of a product a user is currently holding.
I'm doing this in my view
def show_product_details(request, product_name):
product = product.objects.get(Product_name=product_name)
...
profile = Profile.objects.get(user = request.user)
product_holding = profile.holding_set.get(product_name__product_name = product_name)
return render(request, 'productdetails.html', {'product_holding':product_holding ...}
But this isn't returning all the data, but instead just the product_name
.
What am i doing wrong.? :(
CodePudding user response:
In line
product_holding = profile.holding_set.get(product_name__product_name = product_name)
You are accessing Product model (product_name field in Holding model) and then from this model you are accessing field "product_name" which correspond to
product_name = models.CharField(max_length=255, blank=False, unique=True)
in Product model. So you are getting just the name of it.
If you want to get the whole model data then use just:
product_holding = profile.holding_set.get(product_name = product_name)
And the you can access each field by using
{{product_name.product_name}}
{{product_name.product_price}}