Home > front end >  Can't Query and iterate through database
Can't Query and iterate through database

Time:04-04

I am trying to filter only the rows that have the foreign id of 1 or in this case 'Skincare' I have tried both, but no matter what combo I try it either applies no filter, nothing at all shows up, or I get an error that it is not iterable. I want

@views.route("/makeup")
def makeup():
    blogs = Blog.query.filter(Blog.category_id == '1').all()
    
    for date, img, title in blogs:
        date = Blog.date
        img = Blog.fileid
        title = Blog.title

    return render_template('./makeup.html', blogs = blogs)
class Category(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    categories = db.Column(db.String(150), unique = True)
    formss = db.relationship('Blog', backref = 'category', lazy=True) 

    def __repr__(self):
        return '<Category %r>' % self.id
    
    def __init__(self, categories):
        self.categories = categories
        
    

class Blog(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    title = db.Column(db.String(150), unique = True)
    fileid = db.Column(db.String(150), unique = True)
    date = db.Column(db.String(150)) 
    content = db.Column(db.String(150))
    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    

    def __repr__(self):
        return '<Blog %r>' % self.id
    
    def __init__(self, title, fileid, date, content, category):
        self.title = title
        self.fileid = fileid
        self.date = date
        self.content = content
        self.category = category
{% for date, img, title in blogs %}
  
                  
  <div ><div ><img  src="{{url_for('static', filename='uploads/')}}{{img}}"><button >View Post</button></div><p>{{date}}</p><h2>{{title}}</h2></div>
          
  {% endfor %}

CodePudding user response:

I'm not sure what is going on, it does not actually seem to matter if the id is a string or an int. Something like this should work.

@views.route("/makeup")
def makeup():
    blogs = Blog.query.filter(Blog.category_id == '1').all()
    
    # blogs is a list of model objects
    return render_template('./makeup.html', blogs = blogs)

Here we iterate over the list of model objects and use the model to populate the template.

{% for blog in blogs %}
  <div ><div ><img  src="{{url_for('static', filename='uploads/')}}{{ blog.fileid }}"><button >View Post</button></div><p>{{ blog.date }}</p><h2>{{ blog.title }}</h2></div>
{% endfor %}
  • Related