Django: Link between models

Help!

I have the following 2 models:

class Account(models.Model): username = models.OneToOneField(User, primary_key=True, unique=True) receiveaddress = models.CharField(max_length=40, blank=True, null=True, unique=True) balance = models.DecimalField(max_digits=16, decimal_places=8, default=0) def __str__(self): return str(self.username) class Deposits(models.Model): receiveaddress = models.CharField(max_length=40, blank=True, null=True, unique=True) amount = models.DecimalField(max_digits=16, decimal_places=8, default=0) user = ????????????????? created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) confirmed = models.BooleanField(default=False) accounted = models.BooleanField(default=False) def __str__(self): return str(self.receiveaddress) 

Example: Visualization

My problem:

I want "Depositits.user" to automatically refer to the user who owns this "receiving address". In the example, this is TIM. I spent 6 hours trying to figure it out, what am I doing wrong?

Thanks in advance.

+5
source share
1 answer

I think this is just a design issue. Why do you put two fields with the same information, since the user has an account with receiveaddress , adding the user as a foreign key will be more and more clean, I suggest the following:

 class Account(models.Model): username = models.OneToOneField(User, primary_key=True, unique=True) receiveaddress = models.CharField(max_length=40, blank=True, null=True, unique=True) balance = models.DecimalField(max_digits=16, decimal_places=8, default=0) def __str__(self): return str(self.username) class Deposit(models.Model): amount = models.DecimalField(max_digits=16, decimal_places=8, default=0) user = models.ForeignKey(User, related_name="deposits") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) confirmed = models.BooleanField(default=False) accounted = models.BooleanField(default=False) def __str__(self): return str(self.user.account.receiveaddress) 

NB: as a symbol, the model name must always be singular

+3
source

Source: https://habr.com/ru/post/1238485/


All Articles