views:

372

answers:

2

Hi,

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.

+3  A: 

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.

tghw
This needs a constraint to limit it to two Wager instances for the same Bet. I'd suggest adding a method to check this, and raising an exception if someone attempts to save a third Wager for a given Bet.
S.Lott
@S.Lott how would I actually code that? I need to make own Wager.save() method that checks it before calling Model.save(self)?
kender
+1  A: 

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.

Ber