【问题标题】:Django: Setup model with imagesDjango:使用图像设置模型
【发布时间】:2018-10-16 20:39:32
【问题描述】:

我创建了一个博客post 模型,我将在其中添加不同数量的图片。如何设置与picture 模型的关系?

在管理面板中,blog 表单应仅显示附加到此帖子的图片。每张图片可能会在很多帖子中使用。

class Post(models.Model):

    name = models.CharField(max_length=200, null=False)
    article = models.TextField(null=False)
    img = models.ManyToManyField('Picture')

class Picture(models.Model):

    def get_image_path(instance, filename):
        return os.path.join('images', str(instance.id), filename)

    picture = models.ImageField(upload_to=get_image_path, default = 'images/no-img.jpg')

【问题讨论】:

    标签: python django


    【解决方案1】:

    我会这样做:Picture 模型有一个多对多字段,引用 Post

    class Picture(models.Model):
        posts = models.ManyToManyField('Post', related_name='pictures')
        # the rest of the code goes here...
    

    然后您可以访问pictures的帖子列表:

    post = Post.objects.filter(...)
    post.pictures.all()  # this is possible since I've set the related_name 
    # The following can be done as default without `related_name` (and with it)
    post.picture_set.all()
    

    【讨论】:

    • 应该on_delete=models.CASCADEmany-to-many 关系一起使用吗?
    • @camelBack 感谢您指出这一点。级联删除不应用于多对多关系。
    • 猜我必须使用ForeignKey 关系
    • @erik 没问题。我认为关于您的回答,重要的是要注意 many-to-many 关系可以双向 - 这意味着 @Antosha 所做的很好(many-to-many 可以存在于任一模型中)。
    • @AntoshaShmonoff 你想使用级联删除吗?这篇文章可能有用:stackoverflow.com/questions/3937194/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2019-11-28
    • 2018-03-30
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多