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
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
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")
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')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.