1

I am working on a Django project that has multiple users that need to be able to interact with each other, such as sending messages or charging one another. However I am unsure how exactly I am supported to do this. I have a few models like this one:

class Transaction(models.Model):

    #sendingUser = OneToOneField()
    #recievingUser = OneToOneField()
    amount = models.DecimalField(max_digits=11, decimal_places=2)
    time_stamp = models.DateTimeField(auto_now_add=True)
    transaction_cleared = models.BooleanField(default=False, blank=False, null=False)

What I would like to do is have the sendingUser be bound to the user currently logged in and the receiving user be bound to a user that the logged in user specifies. Does doing something like sendingUser = OneToOneField(User) give me the user that is currently logged in? I believe that is what this tutorial is telling me to do, http://blog.robinpercy.com/2010/04/25/django-onetoonefields/, but am not totally sure. What do I put in #recievingUser = OneToOneField() to access a user not currently logged in? I have been trying to find something in the Docs or on SO but I am not exactly sure what I should be searching. Any help would be greatly appreciated.

user3282276
  • 3,674
  • 8
  • 32
  • 48

1 Answers1

1

For a start, you don't want to use OneToOneFields at all. As the name implies, they allow only one user on both sides of the relationship: so each user would only ever be able to have one transaction as a sender and one as a receiver. I imagine you want the ability for any user to have as many transactions as they want, so you should use the ForeignKey field.

But no, neither of these relationships have anything to do with the user that is logged in. Models are descriptions of your data structure: the declaration means "a transaction has a relationship with a user", but nothing there specifies which user. It's up to you, when you create the transaction, to specify which user you want - which can be the one that is logged in, which you'd get via request.user, or a completely arbitrary other user, which you would look up in the database via their ID or username.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895