【发布时间】:2020-04-19 20:24:33
【问题描述】:
我正在学习 Django,并且正在尝试制作一种 wiki 类型的应用程序。在这个 wiki 中有不同类型的模型:角色、物品、法术和冒险。每个模型都有一些相同的字段(如名称、作者、创建日期等)和一些模型独有的字段,如冒险的持续时间、角色的对齐方式等。我遇到的问题是,如果它们是不同的模型然后每次我想制作所有模型共有的东西(比如能够喜欢、收藏、创建、编辑等),然后我必须为每个模型单独编码。有没有一种方法可以创建一种包含每个角色、项目、咒语和冒险的内容模型,以便每次我想制作一个表单或函数时,我只制作一个内容表单或内容函数?
这是一些代码,有些部分是西班牙语,但我翻译了重要部分:
class Character(models.Model):
ALIGNMENT= (
('Legal Bueno', 'Legal Bueno'),
('Legal Neutral', 'Legal Neutral'),
('Legal Malvado', 'Legal Malvado'),
('Neutral Bueno', 'Neutral Bueno'),
('Neutral', 'Neutral'),
('Neutral Malvado', 'Neutral Malvado'),
('Caótico Bueno', 'Caótico Bueno'),
('Caótico Neutral', 'Caótico Neutral'),
('Caótico Malvado', 'Caótico Malvado')
)
name = models.CharField(max_length=50)
author = models.ForeignKey(Usuario, null=True, on_delete=models.CASCADE, editable=False, related_name='personajes')
alignment = models.CharField(max_length=50, choices=ALIGNMENT)
description= models.CharField(max_length=200, null=True)
likes = models.ManyToManyField(Usuario, blank=True, related_name='personaje_likes')
favorites = models.ManyToManyField(Usuario, blank=True, related_name='personaje_favoritos')
class Item(models.Model):
name = models.CharField(max_length=50)
author = models.ForeignKey(Usuario, null=True, on_delete=models.CASCADE, editable=False, related_name='items')
description= models.CharField(max_length=200, null=True)
likes = models.ManyToManyField(Usuario, blank=True, related_name='item_likes')
favorites = models.ManyToManyField(Usuario, blank=True, related_name='item_favoritos')
class Spell(models.Model):
name = models.CharField(max_length=50)
author = models.ForeignKey(Usuario, null=True, on_delete=models.CASCADE, editable=False, related_name='hechizos')
description= models.CharField(max_length=200, null=True)
likes = models.ManyToManyField(Usuario, blank=True, related_name='hechizo_likes')
favorites = models.ManyToManyField(Usuario, blank=True, related_name='hechizo_favoritos')
class Adventure(models.Model):
DURATION = (
('Corta', 'Corta'),
('Mediana', 'Mediana'),
('Larga', 'Larga')
)
name = models.CharField(max_length=50)
author = models.ForeignKey(Usuario, null=True, on_delete=models.CASCADE, editable=False, related_name='aventuras')
duration = models.CharField(max_length=50, choices=DURATION)
description = models.CharField(max_length=200)
likes = models.ManyToManyField(Usuario, blank=True, related_name='aventura_likes')
favorites = models.ManyToManyField(Usuario, blank=True, related_name='aventura_favoritos')
【问题讨论】:
标签: django django-models django-views