gpt4 book ai didi

python - Django:模型之间的引用

转载 作者:太空狗 更新时间:2023-10-30 01:21:03 25 4
gpt4 key购买 nike

帮助!

我有以下两个模型:

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)

示例: Visualization

我的问题:

我希望“Deposits.user”自动引用这个“receiveaddress”所属的用户。在示例中,这是 TIM。我浪费了 6 个小时试图弄明白,我做错了什么?

提前致谢。

最佳答案

我认为这只是一个设计问题。为什么要放置两个具有相同信息的字段,因为 userreceiveaddress 的帐户,将用户添加为外键就足够了,我建议如下:

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)

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

关于python - Django:模型之间的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34328552/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com