codingKID
codingKID

Reputation: 33

how to use models in django for a query

Assume that i have a table usr with feilds name and age table usr

____________
id|name   |age|

1 |dinkan | 12|

____________

my query is

select id from usr where name="dinkan" or age="20";

the corresponding output should be 1

so , my question is how to implement this in django 2.1 using models

Upvotes: 2

Views: 68

Answers (3)

Usman Maqbool
Usman Maqbool

Reputation: 3371

If you want only one result then you should write:

from django.db.models import Q

Model.objects.filter(Q(name="name") | Q(age="age")).first().id

the corresponding output will be 1.

update:

If you want all ids then

from django.db.models import Q

Model.objects.filter(Q(name="name") | Q(age="age")).values("id")

Upvotes: 2

NVS
NVS

Reputation: 401

class User(models.Model):
    user = models.CharField()
    age = models.SmallIntegerField()

your model is something like that i am assuming.

def user():
   user = User.objects.filter(name = 'dinkan', age = '20')

that user will return you a queryset and if you do not have the same name and ages in your DB then you can also use 'get'.

user = User.objects.get(name = 'dinkan', age = '20')

Upvotes: 1

Reza Torkaman Ahmadi
Reza Torkaman Ahmadi

Reputation: 3058

You should use Q operator provided by django models.

Q objects provides you complete control over the where clause of the query.

use an orm query like this:

from django.db.models import Q

Table.objects.filter(Q(name="dinkan") | Q(age="20")).values("id")

you can read more about it here

Upvotes: 4

Related Questions