python - 使用来自另一个 django 模型的输入数据
问题描述
我有两个类模型,用户和资金请求。我正在尝试访问我在 User 类中输入的数据,以便每当我使用 MoneyRequest 类请求资金时,我还可以输入我输入的电子邮件、名字和姓氏以及withdraw_money。
我真的需要来自 User 类的数据,这样每当我查看管理页面时,我就可以看到发送资金请求的用户的姓名。
这是我的models.py
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=100, unique=True)
first_name = models.CharField(max_length=100, blank=True, null=True)
last_name = models.CharField(max_length=100, blank=True, null=True)
class MoneyRequest(models.Model):
date_requested = models.DateTimeField(auto_now_add=True)
withdraw_money = models.DecimalField(null=True, blank=True, max_digits=8, decimal_places=2, help_text='Minimum withdrawal is ₱300.00.', validators=[minimum_money])
这是我对 MoneyRequest 课程的看法
class UserAccountsView(CreateView):
model = MoneyRequest
fields = ['withdraw_money',] # Keep listing whatever fields
template_name = 'users/accounts.html'
def form_valid(self, form):
user = form.save()
user.save()
return redirect('users:user_account', self.request.user.username)
为了获取在 User 类中输入的数据,我应该在 MoneyRequest 类中放入什么?谢谢!
解决方案
在你的moneyrequest模型中添加
user = models.ForeignKey(User, on_delete=models.CASCADE)
,然后你就可以得到所有的User模型数据了。
推荐阅读
- cmake - CLion 无法解析我的 std lib 标头符号
- xamarin - 处置 Device.StartTimer,如果当前页面是从主页重新初始化的
- mysql - 傻瓜的 MySQL 数据库连接问题 - MAMP Pro
- javascript - 如何使用 jQuery (localhost) 获取 oauth access_token?
- javascript - 对 Bootstrap-Vue 表进行排序(星期一、星期二、星期三,而不是按字母顺序)
- javascript - jQuery Uncaught Syntax 错误,无法识别的表达式:+
- docker - 如何在最新的 Raspbian (20-06-2019) 上安装 docker?
- sql-server - 报表生成器:将表格结果打印到 Excel 中的不同工作表中
- javascript - 我的异步在等待调用时返回未定义
- javascript - 在 Youtube 视频上点击海报属性时视频不会播放