Python - Filtering in Many To Many Relationship in Django - Stack Overflow
Python - Filtering in Many To Many Relationship in Django - Stack Overflow
StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free,no registrationrequired.
Takethe2minutetour
IhavetwoclassesLocationandSupplier.Asuppliersuppliesitsproductstooneormorecities.
c l a s s L o c a t i o n ( m o d e l s . M o d e l ) : c i t i e s = m o d e l s . C h a r F i e l d ( m a x _ l e n g t h = 3 0 ) c l a s s S u p p l i e r ( m o d e l s . M o d e l ) : n a m e = m o d e l s . C h a r F i e l d ( m a x _ l e n g t h = 1 0 0 ) s u p p l i e d _ c i t i e s = m o d e l s . M a n y T o M a n y F i e l d ( L o c a t i o n )
NowIhavetogetalltheSuppliersforacity,fromalistofCities.forexample:IfLondonisclicked,I shouldgettheallthesuppliersrelatedtoLondon.HowshouldIdothis?
S u p p l i e r . o b j e c t s . f i l t e r ( s u p p l i e d _ c i t i e s = 1 )
Template:
{ % f o r s e l l e r s i n o b j e c t _ l i s t % } < l i > { { s e l l e r s . n a m e } } < / l i > { % e n d f o r % }
python django
editedDec13'12at10:47
askedDec13'12at7:29 Vino 77 1 8
addcomment
1 Answer
Youwanttouselookupsthatspanrelationships:
d e f m y _ v i e w ( r e q u e s t ) : c i t y _ n a m e = r e q u e s t . G E T . g e t ( ' p l a c e ' ) s e l l e r s = S u p p l i e r . o b j e c t s . f i l t e r ( s u p p l i e d _ c i t i e s _ _ c i t i e s = c i t y _ n a m e ) c o n t e x t = { ' s e l l e r s ' : s e l l e r s } r e t u r n r e n d e r _ t o _ r e s p o n s e ( ' r e s u l t s . h t m l ' , c o n t e x t , c o n t e x t _ i n s t a n c e = R e q u e s t C o n t e x t ( r e q u e s t ) )
Andthenyourtemplate:
{ % f o r s e l l e r i n s e l l e r s % } < l i > { { s e l l e r . n a m e } } < / l i > { % e n d f o r % }
Youmisnamedyourcontextvariable.
stackoverflow.com/questions/13855033/filtering-in-many-to-many-relationship-in-django
1/2
26/03/14
Not the answer you're looking for? Browse other questions tagged python django or ask your own question.
stackoverflow.com/questions/13855033/filtering-in-many-to-many-relationship-in-django
2/2