【问题标题】:How to relate images to database entries如何将图像与数据库条目相关联
【发布时间】:2021-03-27 20:56:50
【问题描述】:

我创建了一个基本的服装电子商务网站,其中产品图像存储在图像文件夹中,产品信息存储在 sqlite 数据库中。目前显示所有衬衫的页面路径如下:

    @app.route('/shirts')
def shirts():
    images = []
    for filename in os.listdir('static/images/shirts'):
        if filename.endswith('.webp'):
            images.append(os.path.join('/static/images/shirts', filename))
        else:
            continue
    descriptions = Shirt.query.all()
    return render_template('shirts.html', info=zip(images, descriptions), title='Shirts')

然后将“信息”变量传递给“衬衫”模板并进行迭代以显示产品图片以及每张图片下方的相关产品描述(内容):

    {% for image, description in info %}
        <div class="item">
            <img src="{{ image }}" class="image">
            <p class="description">{{ description.content }}</p>
        </div>
    {% endfor %}

我意识到这不是一个好主意,因为产品信息与产品图片没有任何关联,并且当我尝试添加更多产品信息(例如尺寸、颜色等)时会给我带来更多问题。

对我来说似乎很明显的解决方案是将图像也存储在数据库中,但是在搜索时,许多人建议这不是要走的路吗?

在现实世界中如何做到这一点,或者至少如何做得更好?

感谢阅读

【问题讨论】:

    标签: python sqlite flask


    【解决方案1】:

    您好,您可以将与产品关联的图像作为字符串添加到数据库中,这可以包含在您的数据库模型中(假设您使用的是 sqlalchemy)

    class Products(db.Model):
        '''
        Products table, this will hold all info about products
        '''
        __searchable__ = ['name']
    
        id          = db.Column(db.Integer, primary_key=True)
        name        = db.Column(db.String(100), nullable=False)
        description = db.Column(db.Text, nullable=True)
        price       = db.Column(db.Float)
        stock       = db.Column(db.Integer, nullable=False, default=1)
        #image is a string, which is the filename of the imagefile
        image2      = db.Column(db.String(100), nullable=True, default='default.jpg')
        image1      = db.Column(db.String(100), nullable=True)
        #vendor details
        vendor_id   = db.Column(db.Integer, db.ForeignKey('vendor.user_id'), nullable=False)
        vendor      = db.relationship('Vendor',lazy=True, uselist=False)
    

    所以现在您可以从数据库查询中获取该产品的所有属性

    products = Products.query.all()
    

    您可以像这样访问模板中的图像名称 (假设您将图像存储在“/static/images”目录中)

    
    {% for product in products %}
      <div>
         <h1>{{product.name}}</h1>
         <img src='static/images/{{product.image1}}'>
      </div>
    {% endfor %}
    

    当然,您可以使用url_for 之类的东西来使其更易于维护, link here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 2012-09-27
      相关资源
      最近更新 更多