0

I'm new in Flask , SQLALchemy i have 1 page that retuern a list of companies , each company has City, Address , and belong to specific industrial sector, and has multiple products

what the best way to Filter results for example based on City , or CITY AND Sector

MY models here

lass Sector (db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), unique=True, nullable=False)
    companies=db.relationship('Company',backref='sector')

class Company(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), unique=True, nullable=False)
    address = db.Column(db.String(),nullable=False)
    city_id=db.Column(db.Integer,db.ForeignKey('city.id'))
    sector_id=db.Column(db.Integer,db.ForeignKey('sector.id'))
    products=db.relationship('Product',backref='company')
   
    
class Certificate(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    type = db.Column(db.String())
    products=db.relationship('Product',backref='certificate')

class Product (db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False) 
    company_id=db.Column(db.Integer,db.ForeignKey('company.id')) 
    certificate_id=db.Column(db.Integer,db.ForeignKey('certificate.id'))

and view page here

{%extends "layout.html"%}
{%block content%}
    
   {%for company in companies%}
   
   
   <article class="media content-section">
    <div class="media-body">
      <div class="article-metadata">
        <a class="mr-2" href="#">{{ company.name }}</a>
        <small class="text-muted">{{ company.sector.name}}</small>
      </div>
      
      <ul>
        {%for product in company.products%}
        <li>{{product.name}}</li>
        {%endfor%}
      </ul>
      <p class="article-content">{{ company.city.name }}</p>
    </div>
  </article>
   
   {%endif%}
   {%endfor%}
   
{%endblock%}

Ahmed
  • 11
  • 1
  • What is your routing like? You can have a search parameter in the routing and use `query.filter` to filter your data. – 21rw Feb 10 '21 at 02:00
  • @app.route('/') def index(): ' companies=Company.query.order_by(Company.name) return render_template ('home.html', companies=companies) – Ahmed Feb 10 '21 at 07:55

1 Answers1

0

Instead of having Company.query.order_by(Company.name) to query all of your data, you could

Company.query.filter(city_id=city_id_value, sector_id=sector_id_value)

The city_id_value and sector_id_value may be provided in the route like

sector_id_value = request.args.get('sector', type = int)
city_id_value = request.args.get('city', type = int)

Flask supports named parameters in urls. See this post for a detailed explaination. If you access the url /?sector=10&city=5, then city_id_value will be 5 and sector_id_value will be 10.

21rw
  • 1,016
  • 1
  • 12
  • 26