加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Django:模型之间的参考

发布时间:2020-12-16 22:54:04 所属栏目:Python 来源:网络整理
导读:救命! 我有以下两种型号: 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_d

救命!

我有以下两种型号:

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)

例:
Visualization

我的问题:

我希望“Deposits.user”自动引用此“receiveaddress”所属的用户.在这个例子中,那是TIM.我浪费了6个小时试图搞清楚,我做错了什么?

提前致谢.

最佳答案
我认为这只是一个设计问题.为什么要放两个具有相同信息的字段,因为用户拥有receiveaddress帐户,将用户添加为外键将足够清晰,我建议如下:

class 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)

注意:作为惯例,模型名称应始终是单数

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读