Compare List

23 views
Skip to first unread message

Adriano Costa dos Reis

unread,
May 5, 2012, 12:22:43 PM5/5/12
to Django users
Hey guys, I'm having a problem that I don't know if there is any
feature that I can use to filter a list in django.
What I'm trying to do is to use a manual get_or_create. I have the
following models:
class STREAM(models.Model):
stream_inds = models.ManyToManyField('STREAM_Ind')
Type = models.CharField(max_length = 5)
Throughput = models.DecimalField(max_digits = 15,
decimal_places = 3)

class STREAM_Ind(models.Model):
Port = models.IntegerField()
Throughput = models.DecimalField(max_digits = 15,
decimal_places = 3)

What I've tried to do so far is this:
try:
qset = (

Q(stream_inds__pk__iexact = ids) &

Q(Type__iexact = type) &

Q(Throughput__iexact = throughput)
)
streams =
STREAM.objects.select_related().filter(qset).distinct().get()
except
STREAM.DoesNotExist:
fields = {

'Type': type,

'Throughput': throughput,
}
form =
STREAMForm(fields)
streams =
form.save()
The third line is where I think the problem is, ids is a variable that
contains a list of id that are supposed to match with all the primary
keys of the STREAM_Ind model. So I can be sure that the data is
already in the database, but the first Q object i think always return
false. Is there some way to do it? (I thought about using the "in"
feature, but I need to make sure all pk are matched in order to
retrieve the object, not just one of them). Is there a feature that
allow me to do that? If not can you guys give me a hint of what am I
supposed to do?

francescortiz

unread,
May 6, 2012, 5:50:19 PM5/6/12
to django...@googlegroups.com
If I am not mistaken, the same way that you would construct a SQL query like

SELECT * FROM table1 t1
INNER JOIN table2 t2 ON t2.t1_id = t1.id
INNER JOIN table3 t3 on t2.t3_id = t3.id
WHERE t3.id = '1'
AND t3.id = '2'
AND t3.id = '3'
AND t3.id = '4'
AND t3.id = '5'


(many AND t3.id = 'X')

you will have to set many Q instances or many filters, one for each id.

also, I believe that if you use Q instances only with & operations, you can just use filter and forget about Q.
Reply all
Reply to author
Forward
0 new messages