Я ищу в Интернете, но я не нашел ответа.
Я пытаюсь использовать contenttype и genericforeignkey, но это не совсем то, что я хотел.
У меня есть имя приложения Категории, и я хочу егоработать со многими приложениями, например: блог, страница событий, страница видео и т.д.
Мой код:
from django.db import models
из django.contrib.contenttypes.fields import GenericForeignKey из django.contrib.contenttypes.models import 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