Home > database >  how to get users id in django model?
how to get users id in django model?

Time:03-03

I need to get id from logged user to filter query in models.how to get users id in django model? Thanks

in models.py:

class Portfo(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
    sell = models.ForeignKey(Sell, on_delete=models.CASCADE, null=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True)
    profit = models.PositiveIntegerField(null=True)
    final_amount = models.IntegerField(null=True)

    def __str__(self):
        return self.product.name

    def final_amount(self):
        final_amount = 0
        buy = Buy.objects.filter(product_id=self.product.id, owner__exact=...)
        sell = Sell.objects.filter(product_id=self.product.id)

CodePudding user response:

I need to get id from logged user to filter query in models.

Models are designed to be request-unaware. If you want to retrieve the user id, you will need to pass it through a parameter, so:

class Portfo(models.Model):
    # …

    def final_amount(self, user_id):
        final_amount = 0
        buy = Buy.objects.filter(product_id=self.product_id, owner_id=user_id)
        sell = Sell.objects.filter(product_id=self.product_id, owner_id=user_id)
        # …

In the view, you can then use the .final_amount(…) method, for example with:

from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404

@login_required
def some_view(request, pk):
    my_porfolio = get_object_or_404(Portfolio, pk=pk)
    final_amount = my_portfolio.final_amount(request.user.id)
    # …
  • Related