我有一个幻灯片模型,我需要在其中添加图片和标题n
次,其中n
是每个幻灯片上的幻灯片数量。这取决于幻灯片。
以下是模型:
class SlideShow(models.Model):
name = models.CharField(blank=False, max_length=50)
slug = models.SlugField(blank=False, max_length=50)
type = models.CharField(choices=SLIDESHOW_TYPES, default=SLIDESHOW_TYPE_DEFAULT, max_length=20)
height = models.IntegerField(blank=False)
width = models.IntegerField(blank=False)
auto_play = models.BooleanField(default=True)
loop_play = models.BooleanField(default=True)
random = models.BooleanField(default=True)
display_time = models.DecimalField(blank=False, decimal_places=3, max_digits=5)
transition_speed = models.DecimalField(blank=False, decimal_places=3, max_digits=5)
music_file = models.FileField(blank=True,upload_to=gen_slideshowimage_upload_dir_func('music'))
music_loop = models.BooleanField(default=True)
slide_count = models.IntegerField()
# repeat the below fields as per the slide_count
image = models.FileField(blank=False,upload_to=gen_slideshowimage_upload_dir_func('images'))
caption = models.CharField(blank=True, max_length=25)
def __unicode__(self):
return self.name
每个幻灯片计数必须重复最后两个字段。
我不想在单独的模型上使用图片并与表格管理员或关系进行关联。如何使用Django实现这一目标?
答案 0 :(得分:4)
使用主/从表是处理此问题的正确方法。 (它叫Many to One Relation):
class SlideShow(models.Model):
name = models.CharField(blank=False, max_length=50)
slug = models.SlugField(blank=False, max_length=50)
type = models.CharField(choices=SLIDESHOW_TYPES, default=SLIDESHOW_TYPE_DEFAULT, max_length=20)
height = models.IntegerField(blank=False)
width = models.IntegerField(blank=False)
auto_play = models.BooleanField(default=True)
loop_play = models.BooleanField(default=True)
random = models.BooleanField(default=True)
display_time = models.DecimalField(blank=False, decimal_places=3, max_digits=5)
transition_speed = models.DecimalField(blank=False, decimal_places=3, max_digits=5)
music_file = models.FileField(blank=True,upload_to=gen_slideshowimage_upload_dir_func('music'))
music_loop = models.BooleanField(default=True)
def slide_count(self):
return len(self.images_set.all())
def __unicode__(self):
return self.name
class Images(modes.Model):
image = models.FileField(blank=False,upload_to=gen_slideshowimage_upload_dir_func('images'))
caption = models.CharField(blank=True, max_length=25)
slideshow = models.ForeignKey(SlideShow, on_delete=models.CASCADE)