SoFunction
Updated on 2024-11-15

django filter filter implementations to display a type of specified field different value way

1, Front-end style

2, html code

{% load asset_filter %}
<div class="col-sm-2">
 <select class="input-sm form-control select2 inline" name="ServiceModel">
 <option value="">module (in software)</option>
 {% for i in 'Ecs'|ecs_model_field_distinct:'ServiceModel' %}
 {% if i.0 %}
 <option value="{{ i.0 }}">{{ i.0 }}</option>
 {% endif %}
 {% endfor %}
 </select>
</div>

3, back-end code

The contents of asset_filter.py are as follows:


@(name='ecs_model_field_distinct')
def ecs_model_field_distinct(model_name, field_name):
 '''
 Gets the distinct value of an attribute field_name of the model_name module object, returning an array of values
 :param model_name.
 :param field_name.
 :return.
 '''
 asset_app = apps.get_app_config('rule')
 return asset_app.get_model(model_name).().values_list(field_name).distinct()

Additional knowledge:Common field constraints for django model classes, and filter filtering and querying

null

When not set, the default setting is False; when set to True, NULL records will be stored in the database table field. The combination of null and blank, null=True,blank=True, means that the field can be empty.

blank

The default setting is False. when set to True, the table field permits no input. When set to False, the table field is a required input

choices

Alternative Settings. Selection list option, if set, the form for this field will necessarily be a drop-down selection. The value must be a tuple with parentheses, where the first field of each tuple will be stored in the database and the second field is displayed to the user.

default

Default value, when set, table fields will be stored in database fields with the contents of this option when there is no user input

can be any data object supported by python.

editable

How it is set to False will not be involved in the validation of the form. The default is set to True

error_messages

This option implements an error message when the checksum is performed. It is the content of the dictionary structure.

help_text

Formation of input prompts in forms

primary_key

Primary Key, set to True, the field will be enabled as a primary key. The default is False

unique

Set to True to enable the setting of no duplicate value input, default is False

unique_for_date

Set the date without duplicate input, default is False

verbose_name

Text labels for fields

validators

Checksum options, used to configure the method of checksum, the list of compositions.

max_length

Maximum input string length

min_length

Minimum input string length

AutoField Auto-value-added id field

primary_key=True Setting options for mandatory

BigAutoField Auto-value-added id field

Support 1 to 9223372036854775807, serial number between

BigIntegerField long orthopedic field

Integer from -9223372036854775808 to 9223372036854775807

BinaryField binary field

Stores in-memory binary data, accessed as python bytes objects

BooleanField boolean field

If a null Boolean input is permitted, replace it with NullBooleadField.

CharFieldVariable-length string fields

max_length There is a maximum input option that must be set

DateFielddate field

auto_now:Django automatically sets the value of this field to the current time every time the object is saved. This is generally used to indicate the "last modified" time. Be aware that the current date is used, not the default value, so the

You cannot change the save time by overriding the default value.

auto_now_add:When an object is first created, Django automatically sets the value of this field to the current time, which is generally used to indicate when the object was created. It uses the same current date, not the default value

DateTimeField Date fields with moments

auto_now=False

auto_now_add=False

When auto_now or auto_now_add is set to True, the field will have editable=True and blank=True settings

; Field for fixed-precision decimal numbers.

It has two mandatory parameters

max_digits:Maximum number of digits allowed for a number

decimal_places:Maximum number of decimal places

For example, to store a number with a maximum value of 999 with two decimal places, you can use the

(..., max_digits=5, decimal_places=2)

DurationField A datetime incremental field storing python timedelta-like data.

EmailField Mail field

FileField File Fields

FilePathField File path field

FloatField fractional part of a number

ImageField Image Fields

IntegerField integer field

GenericIPAddressField ipaddress field

NullBooleanField Boolean field for license null

PositiveIntegerField

0 to 2147483647, a safe integer that supports all database value ranges.

PositiveSmallIntegerField

0 to 32767 A safe short integer that supports all database value ranges.

SlugField

SmallIntegerField short orthopedic field

TextField Remarks type field for storing complex

TimeField time field

URLField URL field

UUIDField

Python UUID Data object, a 32-bit length ID string

mapped field

ForeignKeyField one-to-many field

mapped field

ManyToManyField many-to-many field

mapped field

OneToOneField one-to-one field

Table queries

consult (a document etc)

().order_by("-username") reverse order by username field value

()[:10] slice operation, get 10 people, negative indexing not supported, slicing saves memory, negative slicing not supported

(name=name) get not get an exception, not desirable

get is used to get an object, if you need to get to meet the conditions of some people, you need to use filter

(name="abc")# equal to

(name__exact="abc") People with names strictly equal to "abc"

(name__iexact="abc")# The name is abc but is not case sensitive, you can find ABC, Abc, aBC, which all match the condition

***(name__contains="abc")# People whose names contain "abc"

***(name__icontains="abc")# name contains "abc" and abc is case insensitive

(name__regex="^abc")# regular expression query

(name__iregex="^abc")#Regular expressions are not case-sensitive

****

(age__gt=15)# age > 15

(age__lt=15)# age < 15

(age__gte=15)# age >= 15

(age__lte=15)# age <= 15

(age__ne=15)# age != 15

Archiving of data

times = ('add_time','month',order='desc') Default is positive, desc is reverse.

month means accurate to the month

front end page

{% for time in times %}

{{ }} year {{}} month {{}} day {{}} to the month, and this is always one.

{% endfor %}

filter Filtering when there is more than one condition

Use django's Q object representation or the

from import Q

(Q(name='Zhang San') | Q(age=18))

Query Filter Fields

__exact exact equals like 'aaa'

__iexact exact equals ignore case ilike 'aaa'

__contains Contains like '%aaa%'

__icontains contains Ignore case ilike '%aaa%', but for sqlite, contains has the same effect as icontains.

__gt greater than

__gte greater than or equal to

__lt Less than

__lte less than or equal to

The __in exists within a list.

*****

___startswith to... beginning of a sentence

__istartswith to... Ignore case at the beginning

endswith end

__iendswith starts with... end with ..., ignoring case

__range In... range

Year of the __year date field e.g. .filter(add_time_year ='2018') Filter for adding time year as 2018

Month of the ___month date field

Day of ___day date field

__isnull=True/False

Above this django filter filter to achieve the display of a certain type of specified field different value way is all I share with you, I hope to give you a reference, and I hope you support me more.