You can use Field Lookups
in Django to make specific where
clauses. They are keywords that represent specific SQL
keywords. All Field Lookups
must be specificied with the fieldname
, followed by 2 underscores (__
) characters, and the field lookup
keyword. For example, to get the Persons whose name starts with J
, you can give like this :
Person.objects.filter(first_name__startswith='J').values()
The SQL query
for the above code will be as following :
SELECT * FROM Person WHERE first_name LIKE 'J%';
Other Field Lookups
for reference :
Field Lookup | Description |
---|---|
exact | Matches the exact value of the field. |
iexact | Case-insensitive exact match. |
contains | Matches a substring within the field value. |
icontains | Case-insensitive substring match. |
startswith | Matches values that start with a given substring. |
istartswith | Case-insensitive startswith match. |
endswith | Matches values that end with a given substring. |
iendswith | Case-insensitive endswith match. |
in | Checks if a value is in a list of values. |
gt | Matches values greater than a specified value. |
gte | Matches values greater than or equal to a specified value. |
lt | Matches values less than a specified value. |
lte | Matches values less than or equal to a specified value. |
isnull | Matches NULL values or non-NULL values. |
range | Matches values within a specified range. |
year | Matches records based on the year portion of a date field. |
month | Matches records based on the month portion of a date field. |
day | Matches records based on the day portion of a date field. |
week_day | Matches records based on the day of the week. |
regex | Matches values using a regular expression pattern. |
iregex | Case-insensitive regex match. |
These are the different Field Lookup
Keywords that can be used to select only particular rows from a model.