/ admin / news / article /的OperationalError没有此列:news_article.reporter_id

时间:2019-08-02 18:43:12

标签: django django-models

Models.py

from django.db import models
from django.utils import timezone
class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=255, unique=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

class Reporter(models.Model):
    full_name = models.CharField(max_length=70, db_index=True)

    def __str__(self):
        return self.full_name


class Article(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )
    category = models.ForeignKey(Category, related_name='article', 
                                             on_delete=models.CASCADE)
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
    headline = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, db_index=True)
    image = models.ImageField(upload_to='article/%Y/%m/%d', blank=True)
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, 
                                                      default='draft')

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        return self.headline

我在运行此代码时遇到此错误。 django.db.utils.IntegrityError:表“ news_article”中具有主键“ 1”的行具有无效的外键:news_article.reporter_id包含值“ reporter_id”,而在auth_user.id中没有相应的值。 >

admin.py

from django.contrib import admin
from .models import Category, Article, Reporter

# Register your models here.
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ['name', 'slug']
    prepopulated_fields = {'slug': ('name',)}

@admin.register(Reporter)
class ReporterAdmin(admin.ModelAdmin):
    list_display = ['full_name']


@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    list_display = ['headline', 'slug', 'reporter', 'created', 'updated']
    list_filter = ['headline', 'created', 'updated']
    prepopulated_fields = {'slug': ('headline',)}

0 个答案:

没有答案