在模型中先导入了模型User,然后添加了一个关联用户的字段owner第9行代码,代码如下:
1 from django.db import models 2 from django.contrib.auth.models import User 3 4 # Create your models here. 5 class Topic(models.Model): 6 '''用户学习的主题''' 7 text = models.CharField(max_length=200) 8 date_added = models.DateTimeField(auto_now_add=True) 9 owner = models.ForeignKey('User',on_delete=models.CASCADE) 10 11 def __str__(self): 12 '''返回模型的字符串表示''' 13 return self.text 14 15 class Entry(models.Model): 16 '''学到的有关某个主题的具体知识''' 17 topic = models.ForeignKey('Topic',on_delete=models.CASCADE) 18 text = models.TextField() 19 date_added = models.DateTimeField(auto_now_add=True) 20 21 class Meta: 22 verbose_name_plural = 'entrise' 23 24 def __str__(self): 25 '''返回模型的字符串表示''' 26 if len(self.text) < 50: 27 return self.text 28 else: 29 return self.text[:50]+'...'
再使用python manage.py makemigrations learning_logs迁移数据库,就发生错误了,报错如下:
修改了9行代码,将User的引号去掉了:
并在setting文件中添加了一行代码: SILENCED_SYSTEM_CHECKS = ['fields.E300', 'fields.E307']
1 from django.db import models 2 from django.contrib.auth.models import User 3 4 # Create your models here. 5 class Topic(models.Model): 6 '''用户学习的主题''' 7 text = models.CharField(max_length=200) 8 date_added = models.DateTimeField(auto_now_add=True) 9 owner = models.ForeignKey(User,on_delete=models.CASCADE) 10 11 def __str__(self): 12 '''返回模型的字符串表示''' 13 return self.text 14 15 class Entry(models.Model): 16 '''学到的有关某个主题的具体知识''' 17 topic = models.ForeignKey('Topic',on_delete=models.CASCADE) 18 text = models.TextField() 19 date_added = models.DateTimeField(auto_now_add=True) 20 21 class Meta: 22 verbose_name_plural = 'entrise' 23 24 def __str__(self): 25 '''返回模型的字符串表示''' 26 if len(self.text) < 50: 27 return self.text 28 else: 29 return self.text[:50]+'...'