救命!
我有以下两种型号:
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,unique=True)
amount = models.DecimalField(max_digits=16,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个小时试图搞清楚,我做错了什么?
提前致谢.
最佳答案
我认为这只是一个设计问题.为什么要放两个具有相同信息的字段,因为用户拥有receiveaddress帐户,将用户添加为外键将足够清晰,我建议如下:
原文链接:https://www.f2er.com/python/438459.htmlclass Account(models.Model):
username = models.OneToOneField(User,default=0)
def __str__(self):
return str(self.username)
class Deposit(models.Model):
amount = models.DecimalField(max_digits=16,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)
注意:作为惯例,模型名称应始终是单数