带有django的Mongoengine:DuplicateKeyError

时间:2017-09-14 20:31:31

标签: python django mongodb pymongo

我在Django项目中使用mongoengine(http://mongoengine.org/)。我不知道这是不是一个好主意,但我想我只是试着让它工作,因为似乎没有最新的Django MongoDB实现。运行我的服务器并尝试访问localhost:8000/workoutcal/时出现此错误:

Traceback (most recent call last):
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/views.py", line 18, in calendar
    workouts_in_month = Workout.objects(Q(date__gte=datetime(year=today_year, month=today_month, day=today_day)) & Q(date__lt=datetime(year=today_year, month=today_month+1, day=1)))
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/mongoengine/queryset/manager.py", line 37, in __get__
    queryset = queryset_class(owner, owner._get_collection())
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/mongoengine/document.py", line 204, in _get_collection
    cls.ensure_indexes()
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/mongoengine/document.py", line 834, in ensure_indexes
    collection.create_index(fields, background=background, **opts)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/collection.py", line 1571, in create_index
    self.__create_index(keys, kwargs)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/collection.py", line 1472, in __create_index
    parse_write_concern_error=True)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/collection.py", line 232, in _command
    collation=collation)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/pool.py", line 477, in command
    collation=collation)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/network.py", line 116, in command
    parse_write_concern_error=parse_write_concern_error)
  File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/pymongo/helpers.py", line 203, in _check_command_response
    raise DuplicateKeyError(errmsg, code, response)
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: db.workout index: id_1 dup key: { : null }

我无法理解这个错误。这是否意味着锻炼文件有重复的密钥?这听起来很奇怪,因为这是我的 workoutcal / models.py 的样子:

from mongoengine import *

class Person(Document):
    name = StringField(max_length = 200)
    person_id = IntField(unique = True)
    def __str__(self):
        return str(self.person_id) + self.name

class Lift(EmbeddedDocument):
    lift_id = IntField(unique=True)
    name = StringField(max_length=200) #e.g. bench press, etc
    sets = ListField(IntField()) # No of reps in each set
    def __str__(self):
        return self.name

class Cardio(EmbeddedDocument):
    cardio_id = IntField(unique=True)
    name = StringField(max_length=200)
    duration = IntField() #Number of minutes
    distance = IntField() #Number of metres
    def __str__(self):
        return self.name

class Workout(Document):
    id = IntField(unique=True)
    date = DateTimeField()
    person = ReferenceField(Person)
    lifts = ListField(EmbeddedDocumentField(Lift))
    cardio = ListField(EmbeddedDocumentField(Cardio))
    def __str__(self):
        return str(self.date)+" "+self.person.name

其他可能有用的信息:

我不知道该去哪做connect('db')(连接到我计算机上的mongod数据库)所以我只是把它放在我的 settings.py 中:

from mongoengine import connect
...
connect('db') # <---
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # I kept this since it's needed for admin, etc.
        'NAME': 'mydatabase',
    }
}

workoutcal / urls.py:

app_name = 'workoutcal'
urlpatterns = [
    url(r'^$', views.calendar, name = 'calendar'),
    url(r'^(?P<id>[0-9]+)/$', views.detail, name = 'detail'), #Detail of a workout. Shows lifts, duration, etc. All the attributes.
    url(r'^add/(?P<year>[0-9]+)/(?P<month>[0-9]+)/(?P<day>[0-9]+)/$', views.add, name = 'add'), #Adding a workout for the date in question
    url(r'^edit/(?P<id>[0-9]+)/$', views.edit, name = 'edit'), #Editing an existing workout. id is id of workout object to edit.
]

简而言之,我的问题是:

  1. 为什么我会收到此错误,我该怎么办呢?
  2. 我的Django项目中connect()mongod的正确内容是什么?
  3. 你想以这种方式将mongoenging与django融为一体吗?

1 个答案:

答案 0 :(得分:1)

duplicate key error collection: db.workout index: id_1 dup key: { : null } 在mongo中表示您已使用id = null存储了一个锻炼实体,现在正尝试使用id = null存储另一个锻炼实体。您必须手动清理数据库。之后,看看

class Workout(Document):
    id = IntField(unique=True)

id不是必需的,所以我认为在将实体保存到数据库时没有设置它。将null=False添加到id字段参数以确保它已初始化。或者甚至更好,根本没有id字段,让django为你自动创建一个 - 但不确定,它是如何与mongo一起工作的。