Django涔婱odel鎿嶄綔

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django涔婱odel鎿嶄綔相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/reason' title='reason'>reason   signed   mys   cap   涓ょ   table   its   birt   base   

瀛楁

鎶€鏈垎浜浘鐗? id=
AutoField(Field)
        - int鑷鍒楋紝蹇呴』濉叆鍙傛暟 primary_key=True

    BigAutoField(AutoField)
        - bigint鑷鍒楋紝蹇呴』濉叆鍙傛暟 primary_key=True

        娉細褰搈odel涓鏋滄病鏈夎嚜澧炲垪锛屽垯鑷姩浼氬垱寤轰竴涓垪鍚嶄负id鐨勫垪
        from django.db import models

        class UserInfo(models.Model):
            # 鑷姩鍒涘缓涓€涓垪鍚嶄负id鐨勪笖涓鸿嚜澧炵殑鏁存暟鍒?/span>
            username = models.CharField(max_length=32)

        class Group(models.Model):
            # 鑷畾涔夎嚜澧炲垪
            nid = models.AutoField(primary_key=True)
            name = models.CharField(max_length=32)

    SmallIntegerField(IntegerField):
        - 灏忔暣鏁?-32768 锝?32767

    PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        - 姝e皬鏁存暟 0 锝?32767
    IntegerField(Field)
        - 鏁存暟鍒?鏈夌鍙风殑) -2147483648 锝?2147483647

    PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
        - 姝f暣鏁?0 锝?2147483647

    BigIntegerField(IntegerField):
        - 闀挎暣鍨?鏈夌鍙风殑) -9223372036854775808 锝?9223372036854775807

    BooleanField(Field)
        - 甯冨皵鍊肩被鍨?

    NullBooleanField(Field):
        - 鍙互涓虹┖鐨勫竷灏斿€?

    CharField(Field)
        - 瀛楃绫诲瀷
        - 蹇呴』鎻愪緵max_length鍙傛暟锛?max_length琛ㄧず瀛楃闀垮害

    TextField(Field)
        - 鏂囨湰绫诲瀷

    EmailField(CharField)锛?
        - 瀛楃涓茬被鍨嬶紝Django Admin浠ュ強ModelForm涓彁渚涢獙璇佹満鍒?

    IPAddressField(Field)
        - 瀛楃涓茬被鍨嬶紝Django Admin浠ュ強ModelForm涓彁渚涢獙璇?IPV4 鏈哄埗

    GenericIPAddressField(Field)
        - 瀛楃涓茬被鍨嬶紝Django Admin浠ュ強ModelForm涓彁渚涢獙璇?Ipv4鍜孖pv6
        - 鍙傛暟锛?
            protocol锛岀敤浜庢寚瀹欼pv4鎴朓pv6锛?鈥?/span>both鈥?/span>,"ipv4","ipv6"
            unpack_ipv4锛?濡傛灉鎸囧畾涓篢rue锛屽垯杈撳叆::ffff:192.0.2.1鏃跺€欙紝鍙В鏋愪负192.0.2.1锛屽紑鍚埡鍔熻兘锛岄渶瑕乸rotocol="both"

    URLField(CharField)
        - 瀛楃涓茬被鍨嬶紝Django Admin浠ュ強ModelForm涓彁渚涢獙璇?URL

    SlugField(CharField)
        - 瀛楃涓茬被鍨嬶紝Django Admin浠ュ強ModelForm涓彁渚涢獙璇佹敮鎸?瀛楁瘝銆佹暟瀛椼€佷笅鍒掔嚎銆佽繛鎺ョ锛堝噺鍙凤級

    CommaSeparatedIntegerField(CharField)
        - 瀛楃涓茬被鍨嬶紝鏍煎紡蹇呴』涓洪€楀彿鍒嗗壊鐨勬暟瀛?

    UUIDField(Field)
        - 瀛楃涓茬被鍨嬶紝Django Admin浠ュ強ModelForm涓彁渚涘UUID鏍煎紡鐨勯獙璇?

    FilePathField(Field)
        - 瀛楃涓诧紝Django Admin浠ュ強ModelForm涓彁渚涜鍙栨枃浠跺す涓嬫枃浠剁殑鍔熻兘
        - 鍙傛暟锛?
                path,                      鏂囦欢澶硅矾寰?
                match=None,                姝e垯鍖归厤
                recursive=False,           閫掑綊涓嬮潰鐨勬枃浠跺す
                allow_files=True,          鍏佽鏂囦欢
                allow_folders=False,       鍏佽鏂囦欢澶?

    FileField(Field)
        - 瀛楃涓诧紝璺緞淇濆瓨鍦ㄦ暟鎹簱锛屾枃浠朵笂浼犲埌鎸囧畾鐩綍
        - 鍙傛暟锛?
            upload_to = ""      涓婁紶鏂囦欢鐨勪繚瀛樿矾寰?
            storage = None      瀛樺偍缁勪欢锛岄粯璁jango.core.files.storage.FileSystemStorage

    ImageField(FileField)
        - 瀛楃涓诧紝璺緞淇濆瓨鍦ㄦ暟鎹簱锛屾枃浠朵笂浼犲埌鎸囧畾鐩綍
        - 鍙傛暟锛?
            upload_to = ""      涓婁紶鏂囦欢鐨勪繚瀛樿矾寰?
            storage = None      瀛樺偍缁勪欢锛岄粯璁jango.core.files.storage.FileSystemStorage
            width_field=None,   涓婁紶鍥剧墖鐨勯珮搴︿繚瀛樼殑鏁版嵁搴撳瓧娈靛悕锛堝瓧绗︿覆锛?
            height_field=None   涓婁紶鍥剧墖鐨勫搴︿繚瀛樼殑鏁版嵁搴撳瓧娈靛悕锛堝瓧绗︿覆锛?

    DateTimeField(DateField)
        - 鏃ユ湡+鏃堕棿鏍煎紡 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]

    DateField(DateTimeCheckMixin, Field)
        - 鏃ユ湡鏍煎紡      YYYY-MM-DD

    TimeField(DateTimeCheckMixin, Field)
        - 鏃堕棿鏍煎紡      HH:MM[:ss[.uuuuuu]]

    DurationField(Field)
        - 闀挎暣鏁帮紝鏃堕棿闂撮殧锛屾暟鎹簱涓寜鐓igint瀛樺偍锛孫RM涓幏鍙栫殑鍊间负datetime.timedelta绫诲瀷

    FloatField(Field)
        - 娴偣鍨?

    DecimalField(Field)
        - 10杩涘埗灏忔暟
        - 鍙傛暟锛?
            max_digits锛屽皬鏁版€婚暱搴?
            decimal_places锛屽皬鏁颁綅闀垮害

    BinaryField(Field)
        - 浜岃繘鍒剁被鍨?

瀛楁鍒楄〃
瀛楁鍒楄〃
鎶€鏈垎浜浘鐗? id=
class UnsignedIntegerField(models.IntegerField):
    def db_type(self, connection):
        return 鈥?/span>integer UNSIGNED鈥?/span>

PS: 杩斿洖鍊间负瀛楁鍦ㄦ暟鎹簱涓殑灞炴€э紝Django瀛楁榛樿鐨勫€间负锛?
    鈥?/span>AutoField鈥?/span>: 鈥?/span>integer AUTO_INCREMENT鈥?/span>,
    鈥?/span>BigAutoField鈥?/span>: 鈥?/span>bigint AUTO_INCREMENT鈥?/span>,
    鈥?/span>BinaryField鈥?/span>: 鈥?/span>longblob鈥?/span>,
    鈥?/span>BooleanField鈥?/span>: 鈥?/span>bool鈥?/span>,
    鈥?/span>CharField鈥?/span>: 鈥?/span>varchar(%(max_length)s)鈥?/span>,
    鈥?/span>CommaSeparatedIntegerField鈥?/span>: 鈥?/span>varchar(%(max_length)s)鈥?/span>,
    鈥?/span>DateField鈥?/span>: 鈥?/span>date鈥?/span>,
    鈥?/span>DateTimeField鈥?/span>: 鈥?/span>datetime鈥?/span>,
    鈥?/span>DecimalField鈥?/span>: 鈥?/span>numeric(%(max_digits)s, %(decimal_places)s)鈥?/span>,
    鈥?/span>DurationField鈥?/span>: 鈥?/span>bigint鈥?/span>,
    鈥?/span>FileField鈥?/span>: 鈥?/span>varchar(%(max_length)s)鈥?/span>,
    鈥?/span>FilePathField鈥?/span>: 鈥?/span>varchar(%(max_length)s)鈥?/span>,
    鈥?/span>FloatField鈥?/span>: 鈥?/span>double precision鈥?/span>,
    鈥?/span>IntegerField鈥?/span>: 鈥?/span>integer鈥?/span>,
    鈥?/span>BigIntegerField鈥?/span>: 鈥?/span>bigint鈥?/span>,
    鈥?/span>IPAddressField鈥?/span>: 鈥?/span>char(15)鈥?/span>,
    鈥?/span>GenericIPAddressField鈥?/span>: 鈥?/span>char(39)鈥?/span>,
    鈥?/span>NullBooleanField鈥?/span>: 鈥?/span>bool鈥?/span>,
    鈥?/span>OneToOneField鈥?/span>: 鈥?/span>integer鈥?/span>,
    鈥?/span>PositiveIntegerField鈥?/span>: 鈥?/span>integer UNSIGNED鈥?/span>,
    鈥?/span>PositiveSmallIntegerField鈥?/span>: 鈥?/span>smallint UNSIGNED鈥?/span>,
    鈥?/span>SlugField鈥?/span>: 鈥?/span>varchar(%(max_length)s)鈥?/span>,
    鈥?/span>SmallIntegerField鈥?/span>: 鈥?/span>smallint鈥?/span>,
    鈥?/span>TextField鈥?/span>: 鈥?/span>longtext鈥?/span>,
    鈥?/span>TimeField鈥?/span>: 鈥?/span>time鈥?/span>,
    鈥?/span>UUIDField鈥?/span>: 鈥?/span>char(32)鈥?/span>,
鑷畾涔夋棤绗﹀彿鏁存暟瀛楁
鎶€鏈垎浜浘鐗? id=
1.瑙﹀彂Model涓殑楠岃瘉鍜岄敊璇彁绀烘湁涓ょ鏂瑰紡锛?
        a. Django Admin涓殑閿欒淇℃伅浼氫紭鍏堟牴鎹瓵dmiin鍐呴儴鐨凪odelForm閿欒淇℃伅鎻愮ず锛屽鏋滈兘鎴愬姛锛屾墠鏉ユ鏌odel鐨勫瓧娈靛苟鏄剧ず鎸囧畾閿欒淇℃伅
        b. 浣跨敤ModelForm
        c. 璋冪敤Model瀵硅薄鐨?clean_fields 鏂规硶锛屽锛?
            # models.py
            class UserInfo(models.Model):
                nid = models.AutoField(primary_key=True)
                username = models.CharField(max_length=32)

                email = models.EmailField(error_messages={鈥?/span>invalid鈥?/span>: 鈥?/span>鏍煎紡閿欎簡.鈥?/span>})

            # views.py
            def index(request):
                obj = models.UserInfo(username=鈥?/span>11234鈥?/span>, email=鈥?/span>uu鈥?/span>)
                try:
                    print(obj.clean_fields())
                except Exception as e:
                    print(e)
                return HttpResponse(鈥?/span>ok鈥?/span>)

           # Model鐨刢lean鏂规硶鏄竴涓挬瀛愶紝鍙敤浜庡畾鍒舵搷浣滐紝濡傦細涓婅堪鐨勫紓甯稿鐞嗐€?/span>

    2.Admin涓慨鏀归敊璇彁绀?
        # admin.py
        from django.contrib import admin
        from model_club import models
        from django import forms


        class UserInfoForm(forms.ModelForm):
            age = forms.IntegerField(initial=1, error_messages={鈥?/span>required鈥?/span>: 鈥?/span>璇疯緭鍏ユ暟鍊?鈥?/span>, 鈥?/span>invalid鈥?/span>: 鈥?/span>骞撮緞蹇呴』涓烘暟鍊?鈥?/span>})

            class Meta:
                model = models.UserInfo
                # fields = (鈥榰sername鈥?)
                fields = "__all__"
                exclude = [鈥?/span>title鈥?/span>]
                labels = { 鈥?/span>name鈥?/span>:鈥?/span>Writer鈥?/span>, }
                help_texts = {鈥?/span>name鈥?/span>:鈥?/span>some useful help text.鈥?/span>,}
                error_messages={ 鈥?/span>name鈥?/span>:{鈥?/span>max_length鈥?/span>:"this writer name is too long"} }
                widgets={鈥?/span>name鈥?/span>:Textarea(attrs={鈥?/span>cols鈥?/span>:80,鈥?/span>rows鈥?/span>:20})}

        class UserInfoAdmin(admin.ModelAdmin):
            form = UserInfoForm

        admin.site.register(models.UserInfo, UserInfoAdmin)
娉ㄦ剰浜嬮」

瀛楁鍙傛暟

鎶€鏈垎浜浘鐗? id=
null                鏁版嵁搴撲腑瀛楁鏄惁鍙互涓虹┖
    db_column           鏁版嵁搴撲腑瀛楁鐨勫垪鍚?
    default             鏁版嵁搴撲腑瀛楁鐨勯粯璁ゅ€?
    primary_key         鏁版嵁搴撲腑瀛楁鏄惁涓轰富閿?
    db_index            鏁版嵁搴撲腑瀛楁鏄惁鍙互寤虹珛绱㈠紩
    unique              鏁版嵁搴撲腑瀛楁鏄惁鍙互寤虹珛鍞竴绱㈠紩
    unique_for_date     鏁版嵁搴撲腑瀛楁銆愭棩鏈熴€戦儴鍒嗘槸鍚﹀彲浠ュ缓绔嬪敮涓€绱㈠紩
    unique_for_month    鏁版嵁搴撲腑瀛楁銆愭湀銆戦儴鍒嗘槸鍚﹀彲浠ュ缓绔嬪敮涓€绱㈠紩
    unique_for_year     鏁版嵁搴撲腑瀛楁銆愬勾銆戦儴鍒嗘槸鍚﹀彲浠ュ缓绔嬪敮涓€绱㈠紩

    verbose_name        Admin涓樉绀虹殑瀛楁鍚嶇О
    blank               Admin涓槸鍚﹀厑璁哥敤鎴疯緭鍏ヤ负绌?
    editable            Admin涓槸鍚﹀彲浠ョ紪杈?
    help_text           Admin涓瀛楁鐨勬彁绀轰俊鎭?
    choices             Admin涓樉绀洪€夋嫨妗嗙殑鍐呭锛岀敤涓嶅彉鍔ㄧ殑鏁版嵁鏀惧湪鍐呭瓨涓粠鑰岄伩鍏嶈法琛ㄦ搷浣?
                        濡傦細gf = models.IntegerField(choices=[(0, 鈥?/span>浣曠鈥?/span>),(1, 鈥?/span>澶ц〃濮?/span>鈥?/span>),],default=1)

    error_messages      鑷畾涔夐敊璇俊鎭紙瀛楀吀绫诲瀷锛夛紝浠庤€屽畾鍒舵兂瑕佹樉绀虹殑閿欒淇℃伅锛?
                        瀛楀吀鍋ワ細null, blank, invalid, invalid_choice, unique, and unique_for_date
                        濡傦細{鈥?/span>null鈥?/span>: "涓嶈兘涓虹┖.", 鈥?/span>invalid鈥?/span>: 鈥?/span>鏍煎紡閿欒鈥?/span>}

    validators          鑷畾涔夐敊璇獙璇侊紙鍒楄〃绫诲瀷锛夛紝浠庤€屽畾鍒舵兂瑕佺殑楠岃瘉瑙勫垯
                        from django.core.validators import RegexValidator
                        from django.core.validators import EmailValidator,URLValidator,DecimalValidator,                        MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
                        濡傦細
                            test = models.CharField(
                                max_length=32,
                                error_messages={
                                    鈥?/span>c1鈥?/span>: 鈥?/span>浼樺厛閿欎俊鎭?鈥?/span>,
                                    鈥?/span>c2鈥?/span>: 鈥?/span>浼樺厛閿欎俊鎭?鈥?/span>,
                                    鈥?/span>c3鈥?/span>: 鈥?/span>浼樺厛閿欎俊鎭?鈥?/span>,
                                },
                                validators=[
                                    RegexValidator(regex=鈥?/span>root_d+鈥?/span>, message=鈥?/span>閿欒浜?/span>鈥?/span>, code=鈥?/span>c1鈥?/span>),
                                    RegexValidator(regex=鈥?/span>root_112233d+鈥?/span>, message=鈥?/span>鍙堥敊璇簡鈥?/span>, code=鈥?/span>c2鈥?/span>),
                                    EmailValidator(message=鈥?/span>鍙堥敊璇簡鈥?/span>, code=鈥?/span>c3鈥?/span>), ]
                            )
浠g爜绀轰緥

鍏冧俊鎭?/h2>
鎶€鏈垎浜浘鐗? id=
class UserInfo(models.Model):
        nid = models.AutoField(primary_key=True)
        username = models.CharField(max_length=32)
        class Meta:
            # 鏁版嵁搴撲腑鐢熸垚鐨勮〃鍚嶇О 榛樿 app鍚嶇О + 涓嬪垝绾?+ 绫诲悕
            db_table = "table_name"

            # 鑱斿悎绱㈠紩
            index_together = [
                ("pub_date", "deadline"),
            ]

            # 鑱斿悎鍞竴绱㈠紩
            unique_together = (("driver", "restaurant"),)

            # admin涓樉绀虹殑琛ㄥ悕绉?/span>
            verbose_name

            # verbose_name鍔爏
            verbose_name_plural
浠g爜绀轰緥

澶氳〃鍏崇郴鍙婂弬鏁?/h2>
鎶€鏈垎浜浘鐗? id=
 ForeignKey(ForeignObject) # ForeignObject(RelatedField)
        to,                         # 瑕佽繘琛屽叧鑱旂殑琛ㄥ悕
        to_field=None,              # 瑕佸叧鑱旂殑琛ㄤ腑鐨勫瓧娈靛悕绉?/span>
        on_delete=None,             # 褰撳垹闄ゅ叧鑱旇〃涓殑鏁版嵁鏃讹紝褰撳墠琛ㄤ笌鍏跺叧鑱旂殑琛岀殑琛屼负
                                        - models.CASCADE锛屽垹闄ゅ叧鑱旀暟鎹紝涓庝箣鍏宠仈涔熷垹闄?
                                        - models.DO_NOTHING锛屽垹闄ゅ叧鑱旀暟鎹紝寮曞彂閿欒IntegrityError
                                        - models.PROTECT锛屽垹闄ゅ叧鑱旀暟鎹紝寮曞彂閿欒ProtectedError
                                        - models.SET_NULL锛屽垹闄ゅ叧鑱旀暟鎹紝涓庝箣鍏宠仈鐨勫€艰缃负null锛堝墠鎻怓K瀛楁闇€瑕佽缃负鍙┖锛?
                                        - models.SET_DEFAULT锛屽垹闄ゅ叧鑱旀暟鎹紝涓庝箣鍏宠仈鐨勫€艰缃负榛樿鍊硷紙鍓嶆彁FK瀛楁闇€瑕佽缃粯璁ゅ€硷級
                                        - models.SET锛屽垹闄ゅ叧鑱旀暟鎹紝
                                                      a. 涓庝箣鍏宠仈鐨勫€艰缃负鎸囧畾鍊硷紝璁剧疆锛歮odels.SET(鍊?
                                                      b. 涓庝箣鍏宠仈鐨勫€艰缃负鍙墽琛屽璞$殑杩斿洖鍊硷紝璁剧疆锛歮odels.SET(鍙墽琛屽璞?

                                                        def func():
                                                            return 10

                                                        class MyModel(models.Model):
                                                            user = models.ForeignKey(
                                                                to="User",
                                                                to_field="id"
                                                                on_delete=models.SET(func),)
        related_name=None,          # 鍙嶅悜鎿嶄綔鏃讹紝浣跨敤鐨勫瓧娈靛悕锛岀敤浜庝唬鏇?銆愯〃鍚峗set銆?濡傦細 obj.琛ㄥ悕_set.all()
        related_query_name=None,    # 鍙嶅悜鎿嶄綔鏃讹紝浣跨敤鐨勮繛鎺ュ墠缂€锛岀敤浜庢浛鎹€愯〃鍚嶃€?    濡傦細 models.UserGroup.objects.filter(琛ㄥ悕__瀛楁鍚?1).values(鈥樿〃鍚峗_瀛楁鍚嶁€?
        limit_choices_to=None,      # 鍦ˋdmin鎴朚odelForm涓樉绀哄叧鑱旀暟鎹椂锛屾彁渚涚殑鏉′欢锛?/span>
                                    # 濡傦細
                                            - limit_choices_to={鈥?/span>nid__gt鈥?/span>: 5}
                                            - limit_choices_to=lambda : {鈥?/span>nid__gt鈥?/span>: 5}

                                            from django.db.models import Q
                                            - limit_choices_to=Q(nid__gt=10)
                                            - limit_choices_to=Q(nid=8) | Q(nid__gt=10)
                                            - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption=鈥?/span>root鈥?/span>)
        db_constraint=True          # 鏄惁鍦ㄦ暟鎹簱涓垱寤哄閿害鏉?/span>
        parent_link=False           # 鍦ˋdmin涓槸鍚︽樉绀哄叧鑱旀暟鎹?/span>


    OneToOneField(ForeignKey)
        to,                         # 瑕佽繘琛屽叧鑱旂殑琛ㄥ悕
        to_field=None               # 瑕佸叧鑱旂殑琛ㄤ腑鐨勫瓧娈靛悕绉?/span>
        on_delete=None,             # 褰撳垹闄ゅ叧鑱旇〃涓殑鏁版嵁鏃讹紝褰撳墠琛ㄤ笌鍏跺叧鑱旂殑琛岀殑琛屼负

                                    ###### 瀵逛簬涓€瀵逛竴 ######
                                    # 1. 涓€瀵逛竴鍏跺疄灏辨槸 涓€瀵瑰 + 鍞竴绱㈠紩
                                    # 2.褰撲袱涓被涔嬮棿鏈夌户鎵垮叧绯绘椂锛岄粯璁や細鍒涘缓涓€涓竴瀵逛竴瀛楁
                                    # 濡備笅浼氬湪A琛ㄤ腑棰濆澧炲姞涓€涓猚_ptr_id鍒椾笖鍞竴锛?/span>
                                            class C(models.Model):
                                                nid = models.AutoField(primary_key=True)
                                                part = models.CharField(max_length=12)

                                            class A(C):
                                                id = models.AutoField(primary_key=True)
                                                code = models.CharField(max_length=1)

    ManyToManyField(RelatedField)
        to,                         # 瑕佽繘琛屽叧鑱旂殑琛ㄥ悕
        related_name=None,          # 鍙嶅悜鎿嶄綔鏃讹紝浣跨敤鐨勫瓧娈靛悕锛岀敤浜庝唬鏇?銆愯〃鍚峗set銆?濡傦細 obj.琛ㄥ悕_set.all()
        related_query_name=None,    # 鍙嶅悜鎿嶄綔鏃讹紝浣跨敤鐨勮繛鎺ュ墠缂€锛岀敤浜庢浛鎹€愯〃鍚嶃€?    濡傦細 models.UserGroup.objects.filter(琛ㄥ悕__瀛楁鍚?1).values(鈥樿〃鍚峗_瀛楁鍚嶁€?
        limit_choices_to=None,      # 鍦ˋdmin鎴朚odelForm涓樉绀哄叧鑱旀暟鎹椂锛屾彁渚涚殑鏉′欢锛?/span>
                                    # 濡傦細
                                            - limit_choices_to={鈥?/span>nid__gt鈥?/span>: 5}
                                            - limit_choices_to=lambda : {鈥?/span>nid__gt鈥?/span>: 5}

                                            from django.db.models import Q
                                            - limit_choices_to=Q(nid__gt=10)
                                            - limit_choices_to=Q(nid=8) | Q(nid__gt=10)
                                            - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption=鈥?/span>root鈥?/span>)
        symmetrical=None,           # 浠呯敤浜庡瀵瑰鑷叧鑱旀椂锛宻ymmetrical鐢ㄤ簬鎸囧畾鍐呴儴鏄惁鍒涘缓鍙嶅悜鎿嶄綔鐨勫瓧娈?/span>
                                    # 鍋氬涓嬫搷浣滄椂锛屼笉鍚岀殑symmetrical浼氭湁涓嶅悓鐨勫彲閫夊瓧娈?/span>
                                        models.BB.objects.filter(...)

                                        # 鍙€夊瓧娈垫湁锛歝ode, id, m1
                                            class BB(models.Model):

                                            code = models.CharField(max_length=12)
                                            m1 = models.ManyToManyField(鈥?/span>self鈥?/span>,symmetrical=True)

                                        # 鍙€夊瓧娈垫湁: bb, code, id, m1
                                            class BB(models.Model):

                                            code = models.CharField(max_length=12)
                                            m1 = models.ManyToManyField(鈥?/span>self鈥?/span>,symmetrical=False)

        through=None,               # 鑷畾涔夌涓夊紶琛ㄦ椂锛屼娇鐢ㄥ瓧娈电敤浜庢寚瀹氬叧绯昏〃
        through_fields=None,        # 鑷畾涔夌涓夊紶琛ㄦ椂锛屼娇鐢ㄥ瓧娈电敤浜庢寚瀹氬叧绯昏〃涓偅浜涘瓧娈靛仛澶氬澶氬叧绯昏〃
                                        from django.db import models

                                        class Person(models.Model):
                                            name = models.CharField(max_length=50)

                                        class Group(models.Model):
                                            name = models.CharField(max_length=128)
                                            members = models.ManyToManyField(
                                                Person,
                                                through=鈥?/span>Membership鈥?/span>,
                                                through_fields=(鈥?/span>group鈥?/span>, 鈥?/span>person鈥?/span>),
                                            )

                                        class Membership(models.Model):
                                            group = models.ForeignKey(Group, on_delete=models.CASCADE)
                                            person = models.ForeignKey(Person, on_delete=models.CASCADE)
                                            inviter = models.ForeignKey(
                                                Person,
                                                on_delete=models.CASCADE,
                                                related_name="membership_invites",
                                            )
                                            invite_reason = models.CharField(max_length=64)
        db_constraint=True,         # 鏄惁鍦ㄦ暟鎹簱涓垱寤哄閿害鏉?/span>
        db_table=None,              # 榛樿鍒涘缓绗笁寮犺〃鏃讹紝鏁版嵁搴撲腑琛ㄧ殑鍚嶇О
View Code

ORM鎿嶄綔

鎶€鏈垎浜浘鐗? id=
        # 澧?/span>
        #
        # models.Tb1.objects.create(c1=鈥榵x鈥? c2=鈥榦o鈥?  澧炲姞涓€鏉℃暟鎹紝鍙互鎺ュ彈瀛楀吀绫诲瀷鏁版嵁 **kwargs

        # obj = models.Tb1(c1=鈥榵x鈥? c2=鈥榦o鈥?
        # obj.save()

        # 鏌?/span>
        #
        # models.Tb1.objects.get(id=123)         # 鑾峰彇鍗曟潯鏁版嵁锛屼笉瀛樺湪鍒欐姤閿欙紙涓嶅缓璁級
        # models.Tb1.objects.all()               # 鑾峰彇鍏ㄩ儴
        # models.Tb1.objects.filter(name=鈥榮even鈥? # 鑾峰彇鎸囧畾鏉′欢鐨勬暟鎹?/span>
        # models.Tb1.objects.exclude(name=鈥榮even鈥? # 鑾峰彇鎸囧畾鏉′欢鐨勬暟鎹?/span>

        # 鍒?/span>
        #
        # models.Tb1.objects.filter(name=鈥榮even鈥?.delete() # 鍒犻櫎鎸囧畾鏉′欢鐨勬暟鎹?/span>

        # 鏀?/span>
        # models.Tb1.objects.filter(name=鈥榮even鈥?.update(gender=鈥?鈥?  # 灏嗘寚瀹氭潯浠剁殑鏁版嵁鏇存柊锛屽潎鏀寔 **kwargs
        # obj = models.Tb1.objects.get(id=1)
        # obj.c1 = 鈥?11鈥?/span>
        # obj.save()                                                 # 淇敼鍗曟潯鏁版嵁
鍩烘湰澧炲垹鏀规煡
鎶€鏈垎浜浘鐗? id=
  # 鑾峰彇涓暟
        #
        # models.Tb1.objects.filter(name=鈥榮even鈥?.count()

        # 澶т簬锛屽皬浜?/span>
        #
        # models.Tb1.objects.filter(id__gt=1)              # 鑾峰彇id澶т簬1鐨勫€?/span>
        # models.Tb1.objects.filter(id__gte=1)              # 鑾峰彇id澶т簬绛変簬1鐨勫€?/span>
        # models.Tb1.objects.filter(id__lt=10)             # 鑾峰彇id灏忎簬10鐨勫€?/span>
        # models.Tb1.objects.filter(id__lte=10)             # 鑾峰彇id灏忎簬10鐨勫€?/span>
        # models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 鑾峰彇id澶т簬1 涓?灏忎簬10鐨勫€?/span>

        # in
        #
        # models.Tb1.objects.filter(id__in=[11, 22, 33])   # 鑾峰彇id绛変簬11銆?2銆?3鐨勬暟鎹?/span>
        # models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in

        # isnull
        # Entry.objects.filter(pub_date__isnull=True)

        # contains
        #
        # models.Tb1.objects.filter(name__contains="ven")
        # models.Tb1.objects.filter(name__icontains="ven") # icontains澶у皬鍐欎笉鏁忔劅
        # models.Tb1.objects.exclude(name__icontains="ven")

        # range
        #
        # models.Tb1.objects.filter(id__range=[1, 2])   # 鑼冨洿bettwen and

        # 鍏朵粬绫讳技
        #
        # startswith锛宨startswith, endswith, iendswith,

        # order by
        #
        # models.Tb1.objects.filter(name=鈥榮even鈥?.order_by(鈥榠d鈥?    # asc
        # models.Tb1.objects.filter(name=鈥榮even鈥?.order_by(鈥?id鈥?   # desc

        # group by
        #
        # from django.db.models import Count, Min, Max, Sum
        # models.Tb1.objects.filter(c1=1).values(鈥榠d鈥?.annotate(c=Count(鈥榥um鈥?)
        # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"

        # limit 銆乷ffset
        #
        # models.Tb1.objects.all()[10:20]

        # regex姝e垯鍖归厤锛宨regex 涓嶅尯鍒嗗ぇ灏忓啓
        #
        # Entry.objects.get(title__regex=r鈥榐(An?|The) +鈥?
        # Entry.objects.get(title__iregex=r鈥榐(an?|the) +鈥?

        # date
        #
        # Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
        # Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

        # year
        #
        # Entry.objects.filter(pub_date__year=2005)
        # Entry.objects.filter(pub_date__year__gte=2005)

        # month
        #
        # Entry.objects.filter(pub_date__month=12)
        # Entry.objects.filter(pub_date__month__gte=6)

        # day
        #
        # Entry.objects.filter(pub_date__day=3)
        # Entry.objects.filter(pub_date__day__gte=3)

        # week_day
        #
        # Entry.objects.filter(pub_date__week_day=2)
        # Entry.objects.filter(pub_date__week_day__gte=2)

        # hour
        #
        # Event.objects.filter(timestamp__hour=23)
        # Event.objects.filter(time__hour=5)
        # Event.objects.filter(timestamp__hour__gte=12)

        # minute
        #
        # Event.objects.filter(timestamp__minute=29)
        # Event.objects.filter(time__minute=46)
        # Event.objects.filter(timestamp__minute__gte=29)

        # second
        #
        # Event.objects.filter(timestamp__second=31)
        # Event.objects.filter(time__second=2)
        # Event.objects.filter(timestamp__second__gte=31)
杩涢樁鎿嶄綔
鎶€鏈垎浜浘鐗? id=
# extra
        #
        # extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
        #    Entry.objects.extra(select={鈥榥ew_id鈥? "select col from sometable where othercol > %s"}, select_params=(1,))
        #    Entry.objects.extra(where=[鈥榟eadline=%s鈥榏, params=[鈥楲ennon鈥榏)
        #    Entry.objects.extra(where=["foo=鈥榓鈥?OR bar = 鈥榓鈥?, "baz = 鈥榓鈥?])
        #    Entry.objects.extra(select={鈥榥ew_id鈥? "select id from tb where id > %s"}, select_params=(1,), order_by=[鈥?nid鈥榏)

        # F
        #
        # from django.db.models import F
        # models.Tb1.objects.update(num=F(鈥榥um鈥?+1)


        # Q
        #
        # 鏂瑰紡涓€锛?/span>
        # Q(nid__gt=10)
        # Q(nid=8) | Q(nid__gt=10)
        # Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption=鈥榬oot鈥?

        # 鏂瑰紡浜岋細
        # con = Q()
        # q1 = Q()
        # q1.connector = 鈥極R鈥?/span>
        # q1.children.append((鈥榠d鈥? 1))
        # q1.children.append((鈥榠d鈥? 10))
        # q1.children.append((鈥榠d鈥? 9))
        # q2 = Q()
        # q2.connector = 鈥極R鈥?/span>
        # q2.children.append((鈥榗1鈥? 1))
        # q2.children.append((鈥榗1鈥? 10))
        # q2.children.append((鈥榗1鈥? 9))
        # con.add(q1, 鈥楢ND鈥?
        # con.add(q2, 鈥楢ND鈥?
        #
        # models.Tb1.objects.filter(con)


        # 鎵ц鍘熺敓SQL
        #
        # from django.db import connection, connections
        # cursor = connection.cursor()  # cursor = connections[鈥榙efault鈥榏.cursor()
        # cursor.execute("""SELECT * from auth_user where id = %s""", [1])
        # row = cursor.fetchone()
楂樼骇鎿嶄綔
鎶€鏈垎浜浘鐗? id=
##################################################################
# PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #
##################################################################

def all(self)
    # 鑾峰彇鎵€鏈夌殑鏁版嵁瀵硅薄

def filter(self, *args, **kwargs)
    # 鏉′欢鏌ヨ
    # 鏉′欢鍙互鏄細鍙傛暟锛屽瓧鍏革紝Q

def exclude(self, *args, **kwargs)
    # 鏉′欢鏌ヨ
    # 鏉′欢鍙互鏄細鍙傛暟锛屽瓧鍏革紝Q

def select_related(self, *fields)
     鎬ц兘鐩稿叧锛氳〃涔嬮棿杩涜join杩炶〃鎿嶄綔锛屼竴娆℃€ц幏鍙栧叧鑱旂殑鏁版嵁銆?
     model.tb.objects.all().select_related()
     model.tb.objects.all().select_related(鈥?/span>澶栭敭瀛楁鈥?/span>)
     model.tb.objects.all().select_related(鈥?/span>澶栭敭瀛楁__澶栭敭瀛楁鈥?/span>)

def prefetch_related(self, *lookups)
    鎬ц兘鐩稿叧锛氬琛ㄨ繛琛ㄦ搷浣滄椂閫熷害浼氭參锛屼娇鐢ㄥ叾鎵ц澶氭SQL鏌ヨ鍦≒ython浠g爜涓疄鐜拌繛琛ㄦ搷浣溿€?
            # 鑾峰彇鎵€鏈夌敤鎴疯〃
            # 鑾峰彇鐢ㄦ埛绫诲瀷琛╳here id in (鐢ㄦ埛琛ㄤ腑鐨勬煡鍒扮殑鎵€鏈夌敤鎴稩D)
            models.UserInfo.objects.prefetch_related(鈥?/span>澶栭敭瀛楁鈥?/span>)



            from django.db.models import Count, Case, When, IntegerField
            Article.objects.annotate(
                numviews=Count(Case(
                    When(readership__what_time__lt=treshold, then=1),
                    output_field=CharField(),
                ))
            )

            students = Student.objects.all().annotate(num_excused_absences=models.Sum(
                models.Case(
                    models.When(absence__type=鈥?/span>Excused鈥?/span>, then=1),
                default=0,
                output_field=models.IntegerField()
            )))

def annotate(self, *args, **kwargs)
    # 鐢ㄤ簬瀹炵幇鑱氬悎group by鏌ヨ

    from django.db.models import Count, Avg, Max, Min, Sum

    v = models.UserInfo.objects.values(鈥?/span>u_id鈥?/span>).annotate(uid=Count(鈥?/span>u_id鈥?/span>))
    # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id

    v = models.UserInfo.objects.values(鈥?/span>u_id鈥?/span>).annotate(uid=Count(鈥?/span>u_id鈥?/span>)).filter(uid__gt=1)
    # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

    v = models.UserInfo.objects.values(鈥?/span>u_id鈥?/span>).annotate(uid=Count(鈥?/span>u_id鈥?/span>,distinct=True)).filter(uid__gt=1)
    # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1

def distinct(self, *field_names)
    # 鐢ㄤ簬distinct鍘婚噸
    models.UserInfo.objects.values(鈥?/span>nid鈥?/span>).distinct()
    # select distinct nid from userinfo

    娉細鍙湁鍦≒ostgreSQL涓墠鑳戒娇鐢╠istinct杩涜鍘婚噸

def order_by(self, *field_names)
    # 鐢ㄤ簬鎺掑簭
    models.UserInfo.objects.all().order_by(鈥?/span>-id鈥?/span>,鈥?/span>age鈥?/span>)

def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
    # 鏋勯€犻澶栫殑鏌ヨ鏉′欢鎴栬€呮槧灏勶紝濡傦細瀛愭煡璇?/span>

    Entry.objects.extra(select={鈥?/span>new_id鈥?/span>: "select col from sometable where othercol > %s"}, select_params=(1,))
    Entry.objects.extra(where=[鈥?/span>headline=%s鈥?/span>], params=[鈥?/span>Lennon鈥?/span>])
    Entry.objects.extra(where=["foo=鈥榓鈥?OR bar = 鈥榓鈥?/span>", "baz = 鈥榓鈥?/span>"])
    Entry.objects.extra(select={鈥?/span>new_id鈥?/span>: "select id from tb where id > %s"}, select_params=(1,), order_by=[鈥?/span>-nid鈥?/span>])

 def reverse(self):
    # 鍊掑簭
    models.UserInfo.objects.all().order_by(鈥?/span>-nid鈥?/span>).reverse()
    # 娉細濡傛灉瀛樺湪order_by锛宺everse鍒欐槸鍊掑簭锛屽鏋滃涓帓搴忓垯涓€涓€鍊掑簭


 def defer(self, *fields):
    models.UserInfo.objects.defer(鈥?/span>username鈥?/span>,鈥?/span>id鈥?/span>)
    鎴?
    models.UserInfo.objects.filter(...).defer(鈥?/span>username鈥?/span>,鈥?/span>id鈥?/span>)
    #鏄犲皠涓帓闄ゆ煇鍒楁暟鎹?/span>

 def only(self, *fields):
    #浠呭彇鏌愪釜琛ㄤ腑鐨勬暟鎹?/span>
     models.UserInfo.objects.only(鈥?/span>username鈥?/span>,鈥?/span>id鈥?/span>)
     鎴?
     models.UserInfo.objects.filter(...).only(鈥?/span>username鈥?/span>,鈥?/span>id鈥?/span>)

 def using(self, alias):
     鎸囧畾浣跨敤鐨勬暟鎹簱锛屽弬鏁颁负鍒悕锛坰etting涓殑璁剧疆锛?


##################################################
# PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #
##################################################

def raw(self, raw_query, params=None, translations=None, using=None):
    # 鎵ц鍘熺敓SQL
    models.UserInfo.objects.raw(鈥?/span>select * from userinfo鈥?/span>)

    # 濡傛灉SQL鏄叾浠栬〃鏃讹紝蹇呴』灏嗗悕瀛楄缃负褰撳墠UserInfo瀵硅薄鐨勪富閿垪鍚?/span>
    models.UserInfo.objects.raw(鈥?/span>select id as nid from 鍏朵粬琛?/span>鈥?/span>)

    # 涓哄師鐢烻QL璁剧疆鍙傛暟
    models.UserInfo.objects.raw(鈥?/span>select id as nid from userinfo where nid>%s鈥?/span>, params=[12,])

    # 灏嗚幏鍙栫殑鍒板垪鍚嶈浆鎹负鎸囧畾鍒楀悕
    name_map = {鈥?/span>first鈥?/span>: 鈥?/span>first_name鈥?/span>, 鈥?/span>last鈥?/span>: 鈥?/span>last_name鈥?/span>, 鈥?/span>bd鈥?/span>: 鈥?/span>birth_date鈥?/span>, 鈥?/span>pk鈥?/span>: 鈥?/span>id鈥?/span>}
    Person.objects.raw(鈥?/span>SELECT * FROM some_other_table鈥?/span>, translations=name_map)

    # 鎸囧畾鏁版嵁搴?/span>
    models.UserInfo.objects.raw(鈥?/span>select * from userinfo鈥?/span>, using="default")

    ################### 鍘熺敓SQL ###################
    from django.db import connection, connections
    cursor = connection.cursor()  # cursor = connections[鈥榙efault鈥榏.cursor()
    cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    row = cursor.fetchone() # fetchall()/fetchmany(..)


def values(self, *fields):
    # 鑾峰彇姣忚鏁版嵁涓哄瓧鍏告牸寮?/span>

def values_list(self, *fields, **kwargs):
    # 鑾峰彇姣忚鏁版嵁涓哄厓绁?/span>

def dates(self, field_name, kind, order=鈥?/span>ASC鈥?/span>):
    # 鏍规嵁鏃堕棿杩涜鏌愪竴閮ㄥ垎杩涜鍘婚噸鏌ユ壘骞舵埅鍙栨寚瀹氬唴瀹?/span>
    # kind鍙兘鏄細"year"锛堝勾锛? "month"锛堝勾-鏈堬級, "day"锛堝勾-鏈?鏃ワ級
    # order鍙兘鏄細"ASC"  "DESC"
    # 骞惰幏鍙栬浆鎹㈠悗鐨勬椂闂?/span>
        - year : 骞?01-01
        - month: 骞?鏈?01
        - day  : 骞?鏈?鏃?

    models.DatePlus.objects.dates(鈥?/span>ctime鈥?/span>,鈥?/span>day鈥?/span>,鈥?/span>DESC鈥?/span>)

def datetimes(self, field_name, kind, order=鈥?/span>ASC鈥?/span>, tzinfo=None):
    # 鏍规嵁鏃堕棿杩涜鏌愪竴閮ㄥ垎杩涜鍘婚噸鏌ユ壘骞舵埅鍙栨寚瀹氬唴瀹癸紝灏嗘椂闂磋浆鎹负鎸囧畾鏃跺尯鏃堕棿
    # kind鍙兘鏄?"year", "month", "day", "hour", "minute", "second"
    # order鍙兘鏄細"ASC"  "DESC"
    # tzinfo鏃跺尯瀵硅薄
    models.DDD.objects.datetimes(鈥?/span>ctime鈥?/span>,鈥?/span>hour鈥?/span>,tzinfo=pytz.UTC)
    models.DDD.objects.datetimes(鈥?/span>ctime鈥?/span>,鈥?/span>hour鈥?/span>,tzinfo=pytz.timezone(鈥?/span>Asia/Shanghai鈥?/span>))

    """
    pip3 install pytz
    import pytz
    pytz.all_timezones
    pytz.timezone(‘Asia/Shanghai’)
    """

def none(self):
    # 绌篞uerySet瀵硅薄


####################################
# METHODS THAT DO DATABASE QUERIES #
####################################

def aggregate(self, *args, **kwargs):
   # 鑱氬悎鍑芥暟锛岃幏鍙栧瓧鍏哥被鍨嬭仛鍚堢粨鏋?/span>
   from django.db.models import Count, Avg, Max, Min, Sum
   result = models.UserInfo.objects.aggregate(k=Count(鈥?/span>u_id鈥?/span>, distinct=True), n=Count(鈥?/span>nid鈥?/span>))
   ===> {鈥?/span>k鈥?/span>: 3, 鈥?/span>n鈥?/span>: 4}

def count(self):
   # 鑾峰彇涓暟

def get(self, *args, **kwargs):
   # 鑾峰彇鍗曚釜瀵硅薄

def create(self, **kwargs):
   # 鍒涘缓瀵硅薄

def bulk_create(self, objs, batch_size=None):
    # 鎵归噺鎻掑叆
    # batch_size琛ㄧず涓€娆℃彃鍏ョ殑涓暟
    objs = [
        models.DDD(name=鈥?/span>r11鈥?/span>),
        models.DDD(name=鈥?/span>r22鈥?/span>)
    ]
    models.DDD.objects.bulk_create(objs, 10)

def get_or_create(self, defaults=None, **kwargs):
    # 濡傛灉瀛樺湪锛屽垯鑾峰彇锛屽惁鍒欙紝鍒涘缓
    # defaults 鎸囧畾鍒涘缓鏃讹紝鍏朵粬瀛楁鐨勫€?/span>
    obj, created = models.UserInfo.objects.get_or_create(username=鈥?/span>root1鈥?/span>, defaults={鈥?/span>email鈥?/span>: 鈥?/span>1111111鈥?/span>,鈥?/span>u_id鈥?/span>: 2, 鈥?/span>t_id鈥?/span>: 2})

def update_or_create(self, defaults=None, **kwargs):
    # 濡傛灉瀛樺湪锛屽垯鏇存柊锛屽惁鍒欙紝鍒涘缓
    # defaults 鎸囧畾鍒涘缓鏃舵垨鏇存柊鏃剁殑鍏朵粬瀛楁
    obj, created = models.UserInfo.objects.update_or_create(username=鈥?/span>root1鈥?/span>, defaults={鈥?/span>email鈥?/span>: 鈥?/span>1111111鈥?/span>,鈥?/span>u_id鈥?/span>: 2, 鈥?/span>t_id鈥?/span>: 1})

def first(self):
   # 鑾峰彇绗竴涓?/span>

def last(self):
   # 鑾峰彇鏈€鍚庝竴涓?/span>

def in_bulk(self, id_list=None):
   # 鏍规嵁涓婚敭ID杩涜鏌ユ壘
   id_list = [11,21,31]
   models.DDD.objects.in_bulk(id_list)

def delete(self):
   # 鍒犻櫎

def update(self, **kwargs):
    # 鏇存柊

def exists(self):
   # 鏄惁鏈夌粨鏋?/span>
鍏朵粬

鍏朵粬

鎶€鏈垎浜浘鐗? id=
import pymysql
    from django.db import connection, connections
 
    connection.connect()
    conn = connection.connection
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute("""SELECT * from app01_userinfo""")
    row = cursor.fetchone()
    connection.close()
django鍘熺敓sql鑾峰彇cursor瀛楀吀
鎶€鏈垎浜浘鐗? id=
 # 鏁板瓧鑷
    from django.db.models import F
    models.UserInfo.objects.update(num=F(鈥?/span>num鈥?/span>) + 1)

    # 瀛楃涓叉洿鏂?/span>
    from django.db.models.functions import Concat
    from django.db.models import Value

    models.UserInfo.objects.update(name=Concat(鈥?/span>name鈥?/span>, 鈥?/span>pwd鈥?/span>))
    models.UserInfo.objects.update(name=Concat(鈥?/span>name鈥?/span>, Value(鈥?/span>666鈥?/span>)))
鏁板瓧鑷 瀛楃涓叉洿鏂?/span>
鎶€鏈垎浜浘鐗? id=
# ########### 鍩虹鍑芥暟 ###########

    # 1. Concat锛岀敤浜庡仛绫诲瀷杞崲
    # v = models.UserInfo.objects.annotate(c=Cast(鈥榩wd鈥? FloatField()))

    # 2. Coalesce锛屼粠鍓嶅悜鍚庯紝鏌ヨ绗竴涓笉涓虹┖鐨勫€?/span>
    # v = models.UserInfo.objects.annotate(c=Coalesce(鈥榥ame鈥? 鈥榩wd鈥?)
    # v = models.UserInfo.objects.annotate(c=Coalesce(Value(鈥?66鈥?,鈥榥ame鈥? 鈥榩wd鈥?)

    # 3. Concat锛屾嫾鎺?/span>
    # models.UserInfo.objects.update(name=Concat(鈥榥ame鈥? 鈥榩wd鈥?)
    # models.UserInfo.objects.update(name=Concat(鈥榥ame鈥? Value(鈥?66鈥?))
    # models.UserInfo.objects.update(name=Concat(鈥榥ame鈥? Value(鈥?66鈥?,Value(鈥?99鈥?))

    # 4.ConcatPair锛屾嫾鎺ワ紙浠呬袱涓弬鏁帮級
    # v = models.UserInfo.objects.annotate(c=ConcatPair(鈥榥ame鈥? 鈥榩wd鈥?)
    # v = models.UserInfo.objects.annotate(c=ConcatPair(鈥榥ame鈥? Value(鈥?66鈥?))

    # 5.Greatest锛岃幏鍙栨瘮杈冨ぇ鐨勫€?least 鑾峰彇姣旇緝灏忕殑鍊?
    # v = models.UserInfo.objects.annotate(c=Greatest(鈥榠d鈥? 鈥榩wd鈥?output_field=FloatField()))

    # 6.Length锛岃幏鍙栭暱搴?/span>
    # v = models.UserInfo.objects.annotate(c=Length(鈥榥ame鈥?)

    # 7. Lower,Upper,鍙樺ぇ灏忓啓
    # v = models.UserInfo.objects.annotate(c=Lower(鈥榥ame鈥?)
    # v = models.UserInfo.objects.annotate(c=Upper(鈥榥ame鈥?)

    # 8. Now锛岃幏鍙栧綋鍓嶆椂闂?/span>
    # v = models.UserInfo.objects.annotate(c=Now())

    # 9. substr锛屽瓙搴忓垪
    # v = models.UserInfo.objects.annotate(c=Substr(鈥榥ame鈥?1,2))

    # ########### 鏃堕棿绫诲嚱鏁?###########
    # 1. 鏃堕棿鎴彇锛屼笉淇濈暀鍏朵粬锛欵xtract, ExtractDay, ExtractHour, ExtractMinute, ExtractMonth,ExtractSecond, ExtractWeekDay, ExtractYear,
    # v = models.UserInfo.objects.annotate(c=functions.ExtractYear(鈥榗time鈥?)
    # v = models.UserInfo.objects.annotate(c=functions.ExtractMonth(鈥榗time鈥?)
    # v = models.UserInfo.objects.annotate(c=functions.ExtractDay(鈥榗time鈥?)
    #
    # v = models.UserInfo.objects.annotate(c=functions.Extract(鈥榗time鈥? 鈥榶ear鈥?)
    # v = models.UserInfo.objects.annotate(c=functions.Extract(鈥榗time鈥? 鈥榤onth鈥?)
    # v = models.UserInfo.objects.annotate(c=functions.Extract(鈥榗time鈥? 鈥榶ear_month鈥?)
    """
    MICROSECOND
    SECOND
    MINUTE
    HOUR
    DAY
    WEEK
    MONTH
    QUARTER
    YEAR
    SECOND_MICROSECOND
    MINUTE_MICROSECOND
    MINUTE_SECOND
    HOUR_MICROSECOND
    HOUR_SECOND
    HOUR_MINUTE
    DAY_MICROSECOND
    DAY_SECOND
    DAY_MINUTE
    DAY_HOUR
    YEAR_MONTH
    """

    # 2. 鏃堕棿鎴浘锛屼繚鐣欏叾浠栵細Trunc, TruncDate, TruncDay,TruncHour, TruncMinute, TruncMonth, TruncSecond, TruncYear
    # v = models.UserInfo.objects.annotate(c=functions.TruncHour(鈥榗time鈥?)
    # v = models.UserInfo.objects.annotate(c=functions.TruncDate(鈥榗time鈥?)
    # v = models.UserInfo.objects.annotate(c=functions.Trunc(鈥榗time鈥?鈥榶ear鈥?)
ORM鍑芥暟鐩稿叧
鎶€鏈垎浜浘鐗? id=
 from django.db.models.functions.base import Func
    class CustomeFunc(Func):
        function = 鈥?/span>DATE_FORMAT鈥?/span>
        template = 鈥?/span>%(function)s(%(expressions)s,%(format)s)鈥?/span>

        def __init__(self, expression, **extra):
            expressions = [expression]
            super(CustomeFunc, self).__init__(*expressions, **extra)

    v = models.UserInfo.objects.annotate(c=CustomeFunc(鈥?/span>ctime鈥?/span>,format="鈥?%Y-%%m鈥?/span>"))
ORM鑷畾涔夊嚱鏁?/span>

 

以上是关于Django涔婱odel鎿嶄綔的主要内容,如果未能解决你的问题,请参考以下文章

Django涔婳RM鎿嶄綔

Java鎿嶄綔JSON鏁版嵁--Gson鎿嶄綔JSON鏁版嵁

鎿嶄綔绯荤粺-鎿嶄綔绯荤粺-鍐呮牳涓殑灞忓箷鎵撳嵃(涓?

鏁版嵁搴撶瑪璁?馃搾 MySQL鍩虹鎿嶄綔鍛戒护 鍒嗙被娓呮櫚

鑺傜偣鎿嶄綔

pandas 鎿嶄綔-2