Constructing query

31 views
Skip to first unread message

termopro

unread,
Nov 28, 2014, 9:08:42 AM11/28/14
to django...@googlegroups.com
I have 2 models:
Companies and Tags.

A company may have several tags associated with it, so Tag contains many-to-many relation to Company.

If i'd like to get Tags starting with "A" i'd write:
tags = Tag.objects.filter(name__startswith='A').order_by('name').all()

But how do i get the list of tags (beginning with letter 'A') which are associated with at least 1 company ?

In sql it would be something like:

SELECT * FROM
tag
WHERE
name LIKE 'A%' AND id IN (SELECT tag_id FROM tag_organization)


?

Collin Anderson

unread,
Nov 30, 2014, 2:09:46 PM11/30/14
to django...@googlegroups.com
Hi,

This might work:

Tag.objects.filter(name__startswith='A').exclude(company=None).order_by('name').all()

Collin

termopro

unread,
Dec 1, 2014, 5:45:53 AM12/1/14
to django...@googlegroups.com
Thank you Collin !
It works :)
Reply all
Reply to author
Forward
0 new messages