Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Reference 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 "Deposits.user" to automatically reference the user to which this 'receiveaddress' belongs. In the example, that's TIM. I've wasted 6 hours trying to figure it out, what am I doing wrong?

Thanks in advance.

like image 224
gunth223 Ha Avatar asked Oct 18 '22 20:10

gunth223 Ha


1 Answers

I think it' just a design matter. Why do you put two fields that have the same information, since the user has account with receiveaddress, adding the user as foreign key will be enough and cleaner, 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 convention, models name should be always singular

like image 75
Dhia Avatar answered Oct 21 '22 15:10

Dhia