我是Django的新手,但是我试图用来自其他模型VideoTypes的视频类型替换类别常量。我该怎么办?
from django.db import models
# from django.contrib.auth import get_user_model
# User = get_user_model()
CATEGORIES = (
('Executive Speaker Series', 'Executive Speaker Series'),
('College 101', 'College 101'),
('Fireside Chat', 'Fireside Chat'),
('Other', 'Other')
)
# Create your models here.
class VideoType(models.Model):
type = models.CharField(max_length=255)
def __str__(self):
return self.type
class Video(models.Model):
title = models.CharField(max_length=255)
link = models.CharField(max_length=1000)
category = models.CharField(choices=CATEGORIES, max_length=255)
timestamp = models.DateTimeField(auto_now_add=True)
# owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
答案 0 :(得分:1)
您正在寻找ForeignKey字段。它还需要设置行为,以删除相关模型时的行为,请参见on_delete描述。
VideoType(models.Model):
type = models.CharField(max_length=255)
def __str__(self):
return self.type
class Video(models.Model):
title = models.CharField(max_length=255)
link = models.CharField(max_length=1000)
category = models.ForeignKey(VideoType, on_delete=models.SET_NULL) # category is now referring to VideoType model
timestamp = models.DateTimeField(auto_now_add=True)
答案 1 :(得分:0)
您拥有的实现需要带变量而不是字符串的元组。
将您的CATEGORIES = (
(Executive_Speaker_Series, 'Executive Speaker Series'),
(College_101, 'College 101'),
(Fireside_Chat, 'Fireside Chat'),
(Other, 'Other')
)
变量更改为
{{1}}