Hi Ken,
I’ve decided I want to add some more data.
I have Profile
Product
, Holding
models, and want to add a Transaction
model that is linked to the Profile
, and Holding
model to be able to add purchased amount and price.
I’m not sure what the best way to link these models is to be able to easily present the data within a table.
Models:
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)
product_capture_date = models.DateField(blank=True,null=True)
product_logo_address = models.URLField(max_length=255, blank=True)
def __str__(self):
return str(self.product_name)
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 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)
class Transaction(models.Model):
product = models.ForeignKey(Holding, on_delete=models.CASCADE)
amount = models.FloatField(max_length=50, blank=True, null=True)
price = models.FloatField(max_length=50, blank=True, null=True)
transaction_date = models.DateField(null=True, blank=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
I’ve created the transaction model and linked it with a FK to Holding and Profile - this seems to work for allocating the data to the model and allows me to add multiple transactions to a product for a profile.
But I think there is a better way to work within the view, bearing in mind that a product could have multiple transactions assigned and i wouldn’t all the transactions listed just the total amount and average price.
profile = Profile.objects.get(user = request.user)
transact = Transaction.objects.filter(profile = profile)
So within my table, I want to show the product_name
, transaction.price
, and product_holding
. within the same view.
for item in products:
if item.product_slug is not None:
data = pt.get_product_by_id(item.product_slug)
price = (data['market_data']['current_price']['GBP'])
day_change_percentage = (data['market_data']['price_change_percentage_24h'])
results.append({'price':price,'day_change_percentage':day_change_percentage})
...
else:
pass
Im trying
transactions = Transaction.objects.filter(product_name__product_name = item_product_name)
within the for item in products