我通过互联网搜索,但没有找到答案。
我尝试使用contenttype和genericforeignkey,但这并不是我想要的。
我的应用名称为Category,我希望它可以与许多应用一起使用,例如:博客,事件页面,视频页面等。
当我尝试使用通用外键时,我没有称为“类别”的帖子形式的新字段。
我的代码:
from django.db import models
从django.contrib.contenttypes.fields 导入GenericForeignKey 从django.contrib.contenttypes.models导入ContentType
class Category(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
verbose_name = "Kategorie"
def __str__(self):
return self.title
Blog.models
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericRelation
from categories.models import Category
class Post(models.Model):
STATUS_CHOICES=(
('draft', 'Roboczy'),
('published', 'Opublikowany'),
)
image = models.ImageField(upload_to='images/blog')
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=255)
category = GenericRelation(Category)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
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=10,
choices=STATUS_CHOICES,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title