首页 > 解决方案 > 使用来自另一个 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 类中放入什么?谢谢!

标签: pythondjangodjango-modelsdjango-views

解决方案


在你的moneyrequest模型中添加 user = models.ForeignKey(User, on_delete=models.CASCADE) ,然后你就可以得到所有的User模型数据了。


推荐阅读