django - How to filter Many2Many / Generic Relations properly with Q? -
i have 3 models, taggedobject has genericrelation objecttagbridge. , objecttagbridge has foreignkey tag model.
class taggedobject(models.model): """ class represent tagged object """ tags = generic.genericrelation('objecttagbridge', blank=true, null=true) class objecttagbridge(models.model): """ connect generic object tag. """ # pylint: disable-msg=w0232,r0903 content_type = models.foreignkey(contenttype) object_id = models.positiveintegerfield() content_object = generic.genericforeignkey('content_type', 'object_id') tag = models.foreignkey('tag') class tag(models.model): ... when attaching tag object, creating new objecttagbridge , set foreignkey tag tag want attach. working fine, , can tags attached object easy. when want (filter) objects have tag1 , tag2 tried this:
query = q(tags__tag=tag1) & q(tags__tag=tag2) object_list = taggedobjects.filter(query) but object_list empty, because looking taggedobjects have 1 objecttagbridge 2 tag objects, first tag1 , second tag2.
i application more complex q queries one, think need solution q object. in fact combination of binary conjunctions, like: (...) , ( (...) or not(...))
how can filter correctly? every answer welcome, maybe there different way achieve this.
thx help!!!
if result looking taggedobject tag1 , tag2, consider querying taggedobject instead of querying objecttagbridge. query might like:
results = taggedobject.objects.filter(objecttagbridge__tag = tag1).filter(objecttagbridge__tag = tag2) essentially conducting 2 filters. objects both tag1 , tag2 pass filtering criteria , part of result set.
Comments
Post a Comment