我有 Django 2,其中使用了 Rest Framework 和 Djongo。
可以创建帐户,但是当我尝试查看要更新的已创建帐户列表或对其进行任何操作时,实际上我无法检索帐户列表并在 ID 字段上显示错误。
我认为这是 MongoDB 的问题,那么我该如何解决这个问题?
这是我遇到的错误,后面是我的帐户相关代码
MigrationError at /Accounts/account/ id 请求方法:GET 请求 URL: http://localhost:8000/Accounts/account/ Django 版本:2.2.7 异常类型:MigrationError 异常值:
id 异常位置:C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\sql2mongo\query.py 在 _align_results,第 287 行 Python 可执行文件:C:\Users\PC 001\AppData\Local\Programs\Python \Python38-32\python.exe Python 版本:3.8.0 Python 路径:
['E:\Project\accountingPy', 'C:\Users\PC' '001\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\PC 001\AppData\Local \Programs\Python\Python38-32\DLLs', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\PC 001\AppData\Local\Programs \Python\Python38-32', 'C:\Users\PC 001\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\PC' '001\AppData\Local\Programs\Python\Python38 -32\lib\site-packages'] 服务器时间:Mon, 6 Apr 2020 15:00:38 +0000
存储在数据库中的记录
// 1
{
"_id": ObjectId("5e8b3a0c10fc9f40cdca44be"),
"label": "Mapping",
"owner": "Nasser",
"balance_currency": "USD",
"balance": "23.00",
"desc": "This the Cash account that manage by cash payments",
"status": true,
"created_at": ISODate("2020-04-06T14:17:48.838Z"),
"updated_at": ISODate("2020-04-06T14:17:48.838Z")
}
账户模式
class Account(models.Model):
class Meta:
db_table = 'account'
def __str__(self):
return self.label
label = models.CharField(max_length=20,unique=True)
owner = models.CharField(max_length=20)
balance = MoneyField(max_digits=14, decimal_places=2,
default_currency='USD')
desc = models.CharField(max_length=200, blank=True)
status = models.BooleanField(default=1)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
帐户序列化程序
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['label', 'owner', 'balance',
'desc', 'status', 'created_at', 'updated_at']
网址
router = DefaultRouter()
router.register(r'', AccountViewSet, basename='account')
urlpatterns = router.urls
帐户视图集
class AccountViewSet(viewsets.ViewSet):
def list(self, request):
account = Account.objects.all()
serializer = AccountSerializer(account, many=True)
return JsonResponse(serializer.data, safe=False)
# return HttpResponse("List")
AccountFrom
class AccountForm(ModelForm):
class Meta:
model = Account
fields = ['label', 'owner', 'balance',
'desc', 'status']
基本解决方案 我将 id 字段 none autoIncrement 添加到模型中,问题已得到解决。
id = models.IntegerField(primary_key=True, unique=True)
但我认为它不是很好的解决方案,因为 Id 不是 Auto Increment 并且每次我需要检查最后一个 Id 以获得 Auto Increment ID 字段。如何在 MongoDB 中创建自动增量字段?