Search with OR in Django

Asked

Viewed 210 times

0

Hello I’m developing my 1° application in Django and I’m having difficulty with more complex research in DB.

Here is my MODEL:

class Tag(models.Model):

    objects = GChartsManager()

    idtag = models.IntegerField(db_column='idTAG', primary_key=True, editable=False)  # Field name made lowercase.
    desvio = models.FloatField(db_column='DEVIATION', blank=True, null=True)  # Field name made lowercase.
    tempo_max = models.IntegerField(db_column='TIME_MAX', blank=True, null=True)  # Field name made lowercase.
    conv_rate = models.IntegerField(db_column='CONV_RATE', blank=True, null=True)  # Field name made lowercase.
    taginfo_idtaginfo1 = models.ForeignKey('Taginfo', db_column='tagInfo_idTAGINFO')  # Field name made lowercase.
    datasource_idestacao_meteo = models.ForeignKey(Datasource, db_column='datasource_idDATASOURCE', blank=True, null=True)  # Field name made lowercase.

    def __unicode__(self):
        return u'id = %s / id tagInfo => %s' % (self.idtag, self.taginfo_idtaginfo1)

    class Meta:
        managed = False
        db_table = 'tag'


class Taginfo(models.Model):

    objects = GChartsManager()

    idtaginfo = models.IntegerField(db_column='idTAGINFO', primary_key=True, editable=False)  # Field name made lowercase.
    nome = models.CharField(db_column='NAME', max_length=45)  # Field name made lowercase.
    descricao = models.CharField(db_column='DESCRIPTION', max_length=255, blank=True)  # Field name made lowercase.

    def __unicode__(self):
        return u'name = %s / description = %s' % (self.nome, self.descricao)

    class Meta:
        managed = False
        db_table = 'taginfo'

And I want to do a search finding all the tag s of a multiple Taginfo s, ie the variable tags is actually several objects, always:

tagInfos = Taginfo.objects.filter()
        for tag in tags:
            tagInfos = tagInfos.filter(idtaginfo = tag.taginfo_idtaginfo1.idtaginfo)

But this research does not return me anything. I already asked this question and I was told that this would work or using Q objects, Objects Q but I didn’t understand how I would do this in my case where the number of items is variable, from 0 to n. Thanks in advance for the help

1 answer

3


If you want to get all the tags of a Taginfo is a simple search, since you have a ForeignKey in Tag

tags = Tag.objects.filter(taginfo_idtaginfo1__in=[LIST_OF_IDS])

  • Sorry, I explained wrong the code, I fixed it, it is a search of several Taginfo of various Tags, and I would like to put all these in a single queryset to be passed to the template.

  • tags = Tag.objects.filter(taginfo_idtaginfo1__in=[LIST_OF_IDS])

  • It worked! Thanks @Jair Henrique.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.