Я новичок Django пользователь ...
У меня есть этот код в моем файле models.py
from django.db import models
# Create your models here.
class Topic(models.Model):
top_name = models.CharField(max_length=264, unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL) # added on_delete parameter, because DJANGO > v2.0 is
name = models.CharField(max_length=264, unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage, on_delete=models.SET_NULL) # same on_delete needed to be added otherwise t>python manage.py migrate fails
date = models.DateField()
def __str__(self):
return str(self.date)
Приведенный выше код обновлен для версии Django > 2.0 (ie с on_delete = models.SET_NULL), включенным в качестве аргумента.
Затем я запускаю следующие команды в командной консоли
python manage.py makemigrations registers the changes to your application.
python manage.py migrate
python manage.py shell
>>> from first_app.models import Topic
>>> print(Topic.objects.all())
<QuerySet [Topic: Social Network]>
>>> t = Topic(top_name="Social Network")
>>> t.save()
Это дает следующее журнал ошибок
Traceback (most recent call last):
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: first_app_topic.top_name
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\models\base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\models\base.py", line 784, in save_base
force_update, using, update_fields,
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\models\base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\models\base.py", line 926, in _do_insert
using=using, raw=raw,
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\models\sql\compiler.py", line 1392, in execute_sql
cursor.execute(sql, params)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 100, in execute
return super().execute(sql, params)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: first_app_topic.top_name
почему я получаю эту ошибку и что мне нужно ввести / сделать, чтобы исправить ее, чтобы она сохранилась?
Это часть курса Udemy " Python и Django Fullstack Webdeveloper Bootcamp "
Если я добавлю следующее в admin.py
from django.contrib import admin
from first_app.models import AccessRecord, Topic, Webpage
# Register your models here.
admin.site.register(AccessRecord)
admin.site.register(Topic)
admin.site.register(Webpage)
, а затем выполню
python manage.py createsuperuser
, я получу
SystemCheckError: System check identified some issues:
ERRORS:
first_app.AccessRecord.name: (fields.E320) Field specifies on_delete=SET_NULL, but cannot be null.
HINT: Set null=True argument on the field, or change the on_delete rule.
first_app.Webpage.topic: (fields.E320) Field specifies on_delete=SET_NULL, but cannot be null.
HINT: Set null=True argument on the field, or change the on_delete rule.
Итак, я изменил on_delete = models.SET_NULL на on_delete = models.CASCADE
, а затем перезапустил, и это дало мне
Имя пользователя (оставьте поле пустым, чтобы использовать ' OneWorld '):