如何在django模型中获取用户id?
我需要从登录用户获取 id 来过滤模型中的查询。如何在 django 模型中获取用户 id? 感谢
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
模型被设计为不感知请求。如果要检索用户 ID,则需要通过参数传递它,因此:
在视图中,您可以使用
.final_amount(…)
方法,例如: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:
In the view, you can then use the
.final_amount(…)
method, for example with: