Question

I'm trying to design a model for a application allowing 2 people to bet with each other (I know, sounds stupid...). What I'm wondering about is how to connect the bet with users. The structure is like this

|-------------|       |----------|
|    Bet      |       | User     |
| BetUser1    |       |----------|
| BetUser2    |
| Winner      |
| ...         |
|-------------|

So we got 2 people that bet with each other (both are Users from django auth system) and then, after one of them wins, there's a winner. Now all those 3 fields are of type User, but:

  • Should I make BetUser1 and BetUser2 separate fields, or design some many-to-two relationship here? (with many-to-two being a many-to-many and with some external way of ensuring no more then 2 Users can be assigned to each bet?
  • winner can only be either user 1 or user 2, noone else of course. How should I create this field, yet another ForeignKey(User), or some else?

Just looking for some fresh point of view, as it seems that in such stupid case I'm stuck with the django model system.

Was it helpful?

Solution

I would probably add a third model to represent a specific wager someone has placed, as it is conceivable that more than two people could enter into a bet. It would look something like this:

USER        WAGER              BET
             User (FK(User))    Description
             Bet  (FK(Bet))     Winner (FK (Wager), null=True)
             Amount

Django will automatically generate user.wager_set and bet.wager_set based on the foreign keys. This allows you to easily iterate and display the wagers for a bet, as well as the wagers from each user. You can also add a unique_together constraint on User and Bet in the Wager table so that each user can only make one wager.

When the betting is all done, and a winner has been selected, you just set bet.winner.

In case you run into it, you might see a warning about related_name by having Bet point to Wager and Wager point to Bet. To fix, just add related_name=wagers to Wager.bet.

OTHER TIPS

What you need is a Many-to-Many relation with extra data (e.g. the amount on the wager, the time entered,...)

There is a chaper on this in the excellent Django docs on writing models.

Tyler has already outlined the proper schema for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top