python - Django Views and Model: Create ManyToMany User Balance relationship with all other Users - Who Owes money to who?
问题描述
I have 4 models:
class User(models.Model):
...
class Invite(models.Model):
...
house = models.ForeignKey(
House, related_name="house_invites", on_delete=CASCADE)
user = models.ForeignKey(
User, related_name="invites", on_delete=CASCADE)
class House(models.Model):
...
members = models.ManyToManyField(User, related_name="houses")
class Balance(models.Model):
balance_owed = models.DecimalField(
max_digits=10, decimal_places=2, default=0)
two_users = models.ManyToManyField(User, related_name="between_balance")
As a User joins a house, I want that user to create a balance with ALL other users in the house. Number of Balance instances per User will start to form a triangular number sequence (for ref see https://www.101computing.net/triangular-numbers/ );
The issue with this model is that my template has no way of knowing who owes money to who.
This is where I'm lost! In my views.py I have
this_user = User.objects.get(id=request.session['user_id']) # store User that is logged in and receiving an invite
my_invite = Invite.objects.get(user=this_user) #store invite object associated with House and this_user
all_users = this_house.members.all() # store all current members of house
for user in all_users:
balance_obj = Balance.objects.create()
balance_obj.two_users.add(user)
balance_obj.two_users.add(this_user)
my_invite.house.members.add(this_user) # this_user is the one joining the house
This seems to work just fine, however I have no way of knowing who owes money! :( So if John owes Mary $20, when John logs in, my template should say -$20 owed to Mary; when Mary logs in, it should say +$20 due from John.
I'm guessing this would require some changes to my model perhaps? I just don't know what.
edit: Updated models.py snip to show more info for clarity; updated views.py snip to show more info for clarity
解决方案
推荐阅读
- javascript - ReactJS 如何正确调用多个函数
- json - 从 groovy 中的 JSONArray 中删除特定的 JSONObject
- javascript - 如何使用 setTimeout 中的参数解决承诺
- python - 如何在 django 模型中向 integerField 添加数字?
- azure - Azure ML Compute Instance: How can I safely upgrade the default Azure Ubuntu 16.04 LTS to the latest LTS?
- php - 除 WooCommerce 中的几个特定产品外,最小购物车数量
- php - 如何通过 php 脚本在 Ajax 中发送响应
- html - HTML边距对css没有反应
- scala - Dynamic dataframe with n columns and m rows
- javascript - 如何从隐藏元素中删除无限动画