question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Dynamic filter on foreignkey

See original GitHub issue

I am using Flask-admin and SQLalchemy I want to limit the choices of a foreign key based on a choice of the foreign key of the parent tabeld.

class City(Base):
   __tablename__ = 'city'
   id = Column(Integer, primary_key=True)
   name = Column(String, nullable=False)

   def __unicode__(self):
      return self.name

class Street(Base):
   __tablename__ = 'street'
   id = Column(Integer, primary_key=True)
   name = Column(String, nullable=False)
   city = Column(Integer, ForeignKey(City.id), nullable=False)
   city_ref = relationship(City) 

   def __unicode__(self):
      return self.name

class Adress(Base):
   __tablename__ = 'adress'
   id = Column(Integer, primary_key=True)
   familiyname = Column(String, nullable=False)
   street = Column(Integer, ForeignKey(Street.id), nullable=False)
   street_ref = relationship(Street)
   city_ref = relationship("City", 
              secondary="join(Street,City,Street.city==City.id)",
              primaryjoin="and_(Adress.street==Street.id)",
              secondaryjoin="City.id == Street.city") 

   def __unicode__(self):
      return self.name

Now i want to add admin model to add an adress for a family. but first i want to select the city and based on that choice i want to filter the available streets How can this be done?

admin.add_view(sqla.ModelView(Adress, db.session)) 

This also shows the City but the street column is not filtered when a city is chosen.

Issue Analytics

  • State:open
  • Created 9 years ago
  • Reactions:1
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

5reactions
orenyomtovcommented, Sep 6, 2017

I found a more elegant way to achieve the same goal:

form_args = {
        'street': {
            'query_factory': lambda: db.session.query(Street).filter_by(city = '2')
        }
    }

I hope it helps the next person who find this issue on Google.

1reaction
xqliucommented, Jul 7, 2015

I have found a solution to this by using on_form_prefill together with query_factory, here are the steps

  1. In the admin definition, override the default implementation of on_form_prefill, and in that method, you can get the current object being edited, so you can define the query_factory of another field based on the current defined field, code shown below:
class ReceivingAdmin(ModelView):
        def on_form_prefill(self, form, id):

        # Get field(purchase_order_id) from the current object being edited via form._obj.purchase_order_id
        if form is not None and form._obj is not None and form._obj.purchase_order_id is not None:
            po_id = form._obj.purchase_order_id
            # Define a dynamic query factory based on current data.
            # Please notice since the po_id parameter need to be passed to the function,
            # So functools.partial is used
            form.lines.form.purchase_order_line.kwargs['query_factory'] =\
                partial(PurchaseOrderLine.header_filter, po_id)

And here is the definition of the query factory in the model:

class PurchaseOrderLine(db.Model):
    @staticmethod
    def header_filter(po_id):
        return AppInfo.get_db().session.query(PurchaseOrderLine).filter_by(purchase_order_id=po_id)

By this way, we could control which record will be shown in the purchase order line list based on parameter po_id, and the value of po_id is passed to the query factory function in on_form_prefill.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Django - Dynamic filter Foreign Key choices on previοus user ...
1 Answer 1 ... The self.q in this view is the query that you're typing in the form. Also don't forget to import...
Read more >
is it possible to apply a dynamic filter for a foreign key ...
Hi all. I need to filter a foreign key dropdown menu depending on other attribute value. For example: On Employee ProfitCenter dropdown menu...
Read more >
Dynamic Data Foreign Key Filter - how to limit the # of ... - MSDN
Use [Display(AutoGenerateFilter=false)] attribute for foreign key columns that you don't want to display the drop-down list filters. Wednesday, November 24, ...
Read more >
Django Admin - dynamic select options with foreignkey and ...
Note: One supplier can have multiple substrates. Simply, filtering supplier returns multiple query set each with a different substrate ( ...
Read more >
How to apply dynamic filter for the GridGrouping control with ...
To apply dynamic filter to the Grid Grouping control that has foreign key relation, you need to use the GridDynamicFilter object to wire...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found