救命!
我有以下两种型号:
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)
我的问题:
我希望“Deposits.user”自动引用此“receiveaddress”所属的用户。在这个例子中,那是TIM。我浪费了6个小时试图搞清楚,我做错了什么?
提前致谢。
我认为这只是一个设计问题。为什么你把两个具有相同信息的字段放在一起,因为user
有receiveaddress
帐户,添加用户作为外键将足够和清洁,我建议如下:
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)
注意:作为惯例,模型名称应始终是单数