python - 字段“id”需要一个数字,但得到了 ObjectId
问题描述
我正在研究 djongo,我正在尝试创建一个平台,自动为所有新注册用户分配随机数量(1 到 10 之间)比特币。
我的代码如下:
#views.py
def register_page(request):
if request.user.is_authenticated:
return redirect('order_list')
form = RegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request,'Account successfully created, welcome '+ username)
newUserProfile(username) #<------ this is the function to generate the profile with random BTC
return redirect('login')
context = {'form':form}
return render(request, 'api/register.html', context)
from djongo import models
from django.contrib.auth.models import User
#models.py
class UserProfile(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
BTC = models.FloatField()
balance = models.FloatField()
pending_balance = models.FloatField()
pending_BTC = models.FloatField()
#utils.py
def newUserProfile(username):
user = User.objects.get(username=username)
BTC = round(random.uniform(1,10),2)
profile = UserProfile.objects.create(user=user, BTC=BTC, balance = 0, pending_balance = 0, pending_BTC = 0)
profile.save()
当我按下网页上的注册按钮时,我得到:
Exception Type: TypeError
Exception Value:
Field 'id' expected a number but got ObjectId('606d892cb5d1f464cb7d2050').
但是当我进入数据库时,会定期记录新的配置文件:
# userprofile tab
{"_id":{"$oid":"606d892cb5d1f464cb7d2050"},
"user_id":49,
"BTC":3.26,
"balance":0,
"pending_balance":0,
"pending_BTC":0}
# auth_user tab
{"_id":{"$oid":"606d892cb5d1f464cb7d204f"},
"id":49,
"password":"pbkdf2_sha256$180000$nNwVYtrtPYj0$/wwjhAJk7zUVSj8dFg+tbTE1C1Hnme+zfUbmtH6V/PE=",
"last_login":null,
"is_superuser":false,
"username":"Aokami",
"first_name":"",
"last_name":"",
"email":"Aokami@gmail.com",
"is_staff":false,
"is_active":true,
"date_joined":{"$date":"2021-04-07T10:27:56.590Z"}}
如何解决这个问题,或者至少避免错误页面,因为我无论如何都获得了我需要的东西?
解决方案
_id
django 会自动将字段添加到对象中。您添加了另一个名为 的字段id
,其类型为 number。因此,您不能将 django 的值分配_id
给您的id
字段,因为它的类型不同。了解如何自定义 django 的 id 字段以避免这种重复 -> Automatic primary key fields。
您可以使用 django 文档中的这一行id = models.BigAutoField(primary_key=True)
推荐阅读
- angular - ExpressionChangedAfterItHasBeenCheckedError Angular *ngIf 指令导致错误
- android - GStreamer 管道正在播放,但没有填充回调(仅在 Android 上发生,在 Windows 和 Linux 上有效)
- sql - 无法在 Oracle 查询中按日期分组
- angular - 如何使用 ngFor angular 7 在轮播上显示所有图像数据
- javascript - 如何使用 Node JS 获取已排序的文件路径列表
- reactjs - 在渲染之前插入dom元素?
- linux - 如何在 Azure linux Web 应用上托管 Angular
- node.js - 为什么 jsonwebtoken 会抛出“无效签名”错误?
- python-3.x - 我正在尝试从我的系统导入文件,但每次都显示路径目录错误
- java - Teamcity 代理在构建后断开连接(无法访问代理)