首页 > 解决方案 > 字段“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"}}

如何解决这个问题,或者至少避免错误页面,因为我无论如何都获得了我需要的东西?

标签: pythondjangomongodbdjongo

解决方案


_iddjango 会自动将字段添加到对象中。您添加了另一个名为 的字段id,其类型为 number。因此,您不能将 django 的值分配_id给您的id字段,因为它的类型不同。了解如何自定义 django 的 id 字段以避免这种重复 -> Automatic primary key fields

您可以使用 django 文档中的这一行id = models.BigAutoField(primary_key=True)


推荐阅读