开发者

Query Objects with more than one field values

Basically i want to query for test logs which are Open and Under Process and exclude the Close ones

My Test Model has Status field which is fore开发者_运维问答ign key to BugStatus model as below :

class InspectorTestLog(models.Model):
    expected_result = models.TextField(max_length = 1000, blank = True) 
    status = models.ForeignKey(BugStatus, blank = True , null = True)
    datetime = models.DateTimeField(auto_now_add = True)

class BugStatus(models.Model):
    status = models.CharField(max_length = 50)status
    description = models.TextField(max_length = 1000, blank = True, null = True) 
    def __unicode__(self): 
        return self.status 

I have given three status as 'Open' , 'Closed'and 'Under Process'

How do i query for InspectorTestLog objects with status as ('Open' and 'Under Process') and exclude the 'Close' ones


An easier way is to use __in:

InspectorTestLog.objects.filter(status__status__in=['Open', 'Under Process'])

or .exclude:

InspectorTestLog.objects.exclude(status__status='Closed')


You can use Q objects to combine queries. In you case your query might look as follows:

from django.db.models import Q

test_logs = InspectorTestLog.objects.fiter(Q(status__status='Open') | Q(status__status='Under Process'))

This will retrieve all test_logs with a status of 'Open' or 'Under Process' (and by default exclude those with a status of 'Closed'.)

You could also write a query that just excludes test_logs with a 'Closed' status, which would accomplish the same thing:

test_logs = InspectorTestLog.objects.exclude(status__status='Closed')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜