首页 > 解决方案 > 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

标签: pythondjangoalgorithmdjango-viewsmany-to-many

解决方案


推荐阅读