Django 1.11 - get_or_create中的奇怪行为

时间:2018-03-12 23:42:00

标签: django

我在get_or_create

中看到了一个奇怪的行为

我没有slug='ian-osborn'

的记录
>>> DjProfile.objects.get(slug='ian-osborn')
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<console>", line 1, in <module>
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get
    self.model._meta.object_name
frontend.models.DoesNotExist: DjProfile matching query does not exist.

所以我希望get_or_create能够反对新的DjProfile对象,但我收到Key (slug)=() already exists.错误。

>>> DjProfile.objects.get_or_create(slug='ian-osborn')
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 464, in get_or_create
    return self.get(**lookup), False
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get
    self.model._meta.object_name
frontend.models.DoesNotExist: DjProfile matching query does not exist.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "frontend_djprofile_slug_f04b026a_uniq"
DETAIL:  Key (slug)=() already exists.

DjProfile模型定义如下:

class DjProfile(DateTimeModel):
    name = models.CharField(max_length=150, db_index=True)
    slug = models.SlugField(max_length=50, db_index=True, unique=True)
    ...

    class Meta:
        verbose_name = _('Dj Profile')
        verbose_name_plural = _('Dj Profiles')
        ordering = ('name', )
        unique_together = ('name', 'slug')

    def __str__(self):
        return self.name

我在Django命令中运行类似的查询

from django.core.management.base import BaseCommand
from frontend.models import DjProfile

class Command(BaseCommand):
  ...

我做错了什么?

1 个答案:

答案 0 :(得分:1)

由于let ref = Database.database().reference() let customerRef = ref.child("customerDetails").childByAutoId() customerRef.updateChildValues(["email": emailTextField.text!, "firstName": firstNTextField.text!]) 字段是必需的,您应该将其作为name的参数。