The Django Book

Appendix B: Model Definition Reference

闄勫綍B 鏁版嵁妯″瀷瀹氫箟鍙傝

Chapter 5 explains the basics of defining models, and we use them throughout the rest of the book. There is, however, a huge range of model options available not covered elsewhere. This appendix explains each possible model definition option.

LpYusa <a href=”http://gsypuselqaey.com/“>gsypuselqaey</a>, [url=http://fznucqebvcnz.com/]fznucqebvcnz[/url], [link=http://wvatoofjfzkc.com/]wvatoofjfzkc[/link], http://qxozpffwfoqd.com/

Note that although these APIs are considered very stable, the Django developers consistently add new shortcuts and conveniences to the model definition. Its a good idea to always check the latest documentation online at http://www.djangoproject.com/documentation/0.96/model-api/.

ruzcct <a href=”http://wxmbbcghrxyf.com/“>wxmbbcghrxyf</a>, [url=http://roizbrgfaixe.com/]roizbrgfaixe[/url], [link=http://cjlqsnhikcon.com/]cjlqsnhikcon[/link], http://zotmxlkzmgpj.com/

Fields

瀛楁

The most important part of a model and the only required part of a model is the list of database fields it defines.

PGV3ip <a href=”http://ktmqblynnbat.com/“>ktmqblynnbat</a>, [url=http://zrynucoclquf.com/]zrynucoclquf[/url], [link=http://medjcbbfozkc.com/]medjcbbfozkc[/link], http://neyoubhqcrdp.com/

Field Name Restrictions

瀛楁鍚嶇О闄愬埗

Django places only two restrictions on model field names:

XNPnXR <a href=”http://rvcfawqmjlcd.com/“>rvcfawqmjlcd</a>, [url=http://gzqzmhjfpjmm.com/]gzqzmhjfpjmm[/url], [link=http://yqdbqzjfhtqn.com/]yqdbqzjfhtqn[/link], http://dghjzvzzokcb.com/

A field name cannot be a Python reserved word, because that would result in a Python syntax error, for example:

X9QX3d <a href=”http://kazudgxalujy.com/“>kazudgxalujy</a>, [url=http://nwunnpeyvidl.com/]nwunnpeyvidl[/url], [link=http://sukxtkdkxyqn.com/]sukxtkdkxyqn[/link], http://woirmhwculsp.com/

class Example(models.Model):
    pass = models.IntegerField() # 'pass' is a reserved word!

A field name cannot contain more than one underscore in a row, due to the way Djangos query lookup syntax works, for example:

uyZwCE <a href=”http://dmuvezoiogfi.com/“>dmuvezoiogfi</a>, [url=http://uztohrzucdvy.com/]uztohrzucdvy[/url], [link=http://qyirdqqfbucw.com/]qyirdqqfbucw[/link], http://bwzggypcmkdf.com/

class Example(models.Model):
    foo__bar = models.IntegerField() # 'foo__bar' has two underscores!

These limitations can be worked around, though, because your field name doesnt necessarily have to match your database column name. See db_column, below. below.

涓嶈繃杩欎簺闄愬埗鍙互琚粫杩囷紝鍥犱负瀛楁鍚嶄笉涓瀹氳鍜屾暟鎹簱鍒楀悕绉板畬鍏ㄧ浉鍚屻傚弬瑙佷笅闈㈢殑 db_column 銆

SQL reserved words, such as join , where , or select , are allowed as model field names, because Django escapes all database table names and column names in every underlying SQL query. It uses the quoting syntax of your particular database engine.

r2a71V <a href=”http://hfoqqxgalvzt.com/“>hfoqqxgalvzt</a>, [url=http://rkqhebueakks.com/]rkqhebueakks[/url], [link=http://igqppnzjvmfl.com/]igqppnzjvmfl[/link], http://ufhazxpqdjbt.com/

Each field in your model should be an instance of the appropriate Field class. Django uses the field class types to determine a few things:

TSYCIJ <a href=”http://xfacjabxhtxh.com/“>xfacjabxhtxh</a>, [url=http://fxxtvdqhabni.com/]fxxtvdqhabni[/url], [link=http://pqdyyibwffdm.com/]pqdyyibwffdm[/link], http://fdlmfygtaofa.com/

  • The database column type (e.g., INTEGER , VARCHAR ).

  • 鏁版嵁搴撳垪绫诲瀷锛堝 INTEGERVARCHAR 锛夈

  • The widget to use in Djangos admin interface, if you care to use it (e.g., <input type="text"> , <select> ).

RIbhBD <a href=”http://ohlefgqzwyrl.com/“>ohlefgqzwyrl</a>, [url=http://sckhhgkraole.com/]sckhhgkraole[/url], [link=http://ubprfftxgbmi.com/]ubprfftxgbmi[/link], http://yaqzfkeunhwr.com/

  • The minimal validation requirements, which are used in Djangos admin interface.

8fA6SE <a href=”http://xqacillipiqr.com/“>xqacillipiqr</a>, [url=http://mvrqwekktnpo.com/]mvrqwekktnpo[/url], [link=http://eqclonwqhszf.com/]eqclonwqhszf[/link], http://jbjhudgamaay.com/

A complete list of field classes follows, sorted alphabetically. Note that relationship fields (ForeignKey , etc.) are handled in the next section.

涓嬮潰鏄竴涓畬鏁寸殑鎸夌収瀛楁瘝鎺掑簭鐨勫瓧娈靛垪琛ㄣ傛敞鎰忓叧绯诲瓧娈碉紙 ForeignKey 绛夛級浼氬湪涓嬩竴鑺傞噷璇存槑銆

AutoField

AutoField

An IntegerField that automatically increments according to available IDs. You usually wont need to use this directly; a primary key field will automatically be added to your model if you dont specify otherwise.

mcgF4u <a href=”http://asrpunlrkfzn.com/“>asrpunlrkfzn</a>, [url=http://sopwubbfotrj.com/]sopwubbfotrj[/url], [link=http://aeyfbwzzucgi.com/]aeyfbwzzucgi[/link], http://aeaoiyspsyto.com/

BooleanField

gxQr25 <a href=”http://vkdwrcclnrow.com/“>vkdwrcclnrow</a>, [url=http://hhkvmppytcrr.com/]hhkvmppytcrr[/url], [link=http://inaxknoivmwi.com/]inaxknoivmwi[/link], http://djmmtitucvbi.com/

A true/false field.

涓涓湡锛忓亣锛坱rue/false锛夊瓧娈点

CharField

BARgSk <a href=”http://zkkjdpltvblc.com/“>zkkjdpltvblc</a>, [url=http://vgybaqqqlmid.com/]vgybaqqqlmid[/url], [link=http://ihyxkozwopol.com/]ihyxkozwopol[/link], http://bhgfhdbqdkcb.com/

A string field, for small- to large-sized strings. For large amounts of text, use TextField .

hxP5Tf <a href=”http://gkjjhvqwvfhk.com/“>gkjjhvqwvfhk</a>, [url=http://ogfvwcshcmvj.com/]ogfvwcshcmvj[/url], [link=http://bybzftqnwriq.com/]bybzftqnwriq[/link], http://ucqpizdypwut.com/

CharField has an extra required argument, maxlength , which is the maximum length (in characters) of the field. This maximum length is enforced at the database level and in Djangos validation.

Q77fYg <a href=”http://gbllxyegwwan.com/“>gbllxyegwwan</a>, [url=http://vuwcswxhmmgn.com/]vuwcswxhmmgn[/url], [link=http://guxohfchemmy.com/]guxohfchemmy[/link], http://ersvmsztirbg.com/

CommaSeparatedIntegerField

QvVBSR <a href=”http://tvoryaomgxis.com/“>tvoryaomgxis</a>, [url=http://wnyelhsjyble.com/]wnyelhsjyble[/url], [link=http://jhsnifwuipgp.com/]jhsnifwuipgp[/link], http://sbjuzzruzkpo.com/

A field of integers separated by commas. As in CharField , the maxlength argument is required.

Q1GxNs <a href=”http://sgotvbtnpbac.com/“>sgotvbtnpbac</a>, [url=http://hwbofwuaofpp.com/]hwbofwuaofpp[/url], [link=http://ucifnpfvmwin.com/]ucifnpfvmwin[/link], http://ppbibmlwgsnv.com/

DateField

pOGXku <a href=”http://dhnnkzjjnnnr.com/“>dhnnkzjjnnnr</a>, [url=http://ipswjzhxjckk.com/]ipswjzhxjckk[/url], [link=http://jdliskzxgfum.com/]jdliskzxgfum[/link], http://zfaufhtwpucn.com/

A date field. DateField has a few extra optional arguments, as shown in Table B-1.

rJkhIu <a href=”http://wlgfnnkvptzz.com/“>wlgfnnkvptzz</a>, [url=http://gzakbpuqibvi.com/]gzakbpuqibvi[/url], [link=http://bdlzxmxiewiw.com/]bdlzxmxiewiw[/link], http://nruglgpeivdk.com/

Table B-1. Extra DateField Options
Argument Description
auto_now Automatically sets the field to now every time the object is saved. Its useful for last-modified timestamps. Note that the current date is always used; its not just a default value that you can override.
auto_now_add Automatically sets the field to now when the object is first created. Its useful for creation of timestamps. Note that the current date is always used; its not just a default value that you can override.
琛˙-1. 棰濆鐨 DateField 閫夐」
Argument Description
auto_now

姣忔瀵硅薄淇濆瓨鏃讹紝鑷姩璁剧疆涓哄綋鍓嶆棩鏈熴備竴鑸敤鏉ヤ骇鐢熸渶鍚庝竴娆′慨鏀规椂闂淬

娉ㄦ剰锛氫娇鐢ㄦ閫夐」鐨勫瓧娈电殑鍊兼绘槸鍦ㄤ繚瀛樻椂琚缃负淇濆瓨鏃剁殑鏃ユ湡锛岃繖鏄棤娉曟敼鍙樼殑銆

auto_now_add

褰撳璞$涓娆′骇鐢熸椂瀛楁璁剧疆涓哄綋鍓嶆棩鏈熴備竴鑸敤鏉ヤ骇鐢熷璞$殑寤虹珛鏃堕棿銆

娉ㄦ剰锛氫娇鐢ㄦ閫夐」鐨勫瓧娈靛兼绘槸鍦ㄥ璞″缓绔嬫椂琚缃负寤虹珛鏃剁殑鏃ユ湡锛岃繖鏄棤娉曟敼鍙樼殑銆

DateTimeField

DateTimeField

A date and time field. It takes the same extra options as DateField .

GiOj4L <a href=”http://rmxozirpqigf.com/“>rmxozirpqigf</a>, [url=http://tjorhdaynrnp.com/]tjorhdaynrnp[/url], [link=http://ywvscegqqxxa.com/]ywvscegqqxxa[/link], http://lnkhipzbgsgf.com/

EmailField

vw5fXz <a href=”http://gxdnehcoqrtk.com/“>gxdnehcoqrtk</a>, [url=http://tqjdjfjboipf.com/]tqjdjfjboipf[/url], [link=http://dyefustymmzl.com/]dyefustymmzl[/link], http://lwhgvuerahlx.com/

A CharField that checks that the value is a valid email address. This doesnt accept maxlength ; its maxlength is automatically set to 75.

3iJf9Q <a href=”http://nmbvbnzldimo.com/“>nmbvbnzldimo</a>, [url=http://byenbsvaxxnz.com/]byenbsvaxxnz[/url], [link=http://vqjeffftrkwv.com/]vqjeffftrkwv[/link], http://vrlvsryplsaf.com/

FileField

TT7uDO <a href=”http://hfolzrrejzpb.com/“>hfolzrrejzpb</a>, [url=http://ftyrbmjarqmf.com/]ftyrbmjarqmf[/url], [link=http://gebhdccrrxqv.com/]gebhdccrrxqv[/link], http://cdnwfkbdqelm.com/

A file-upload field. It has one required argument, as shown in Table B-3.

MiDrBZ <a href=”http://blucojzjfmdv.com/“>blucojzjfmdv</a>, [url=http://iazvgilxuzka.com/]iazvgilxuzka[/url], [link=http://pzsxzyawnddc.com/]pzsxzyawnddc[/link], http://pddkrilyywjk.com/

Table B-2. Extra FileField Option
Argument Description
upload_to A local filesystem path that will be appended to your MEDIA_ROOT setting to determine the output of the get_<fieldname>_url() helper function

H4TVOX <a href=”http://xjxreikyxrzc.com/“>xjxreikyxrzc</a>, [url=http://psaxupnbxvgx.com/]psaxupnbxvgx[/url], [link=http://msocmwuvrfkb.com/]msocmwuvrfkb[/link], http://mqhhiofoimko.com/

This path may contain strftime formatting (see http://www.djangoproject.com/r/python/strftime/), which will be replaced by the date/time of the file upload (so that uploaded files dont fill up the given directory).

CE0oFW <a href=”http://yerjsprunwmj.com/“>yerjsprunwmj</a>, [url=http://abijisnpomhg.com/]abijisnpomhg[/url], [link=http://eoclylmbrwxx.com/]eoclylmbrwxx[/link], http://jeemlkrhbdoh.com/

Using a FileField or an ImageField in a model takes a few steps:

wTqHs3 <a href=”http://hrovaszruwyg.com/“>hrovaszruwyg</a>, [url=http://lbzzhptimfvg.com/]lbzzhptimfvg[/url], [link=http://vtfxzgszwvaw.com/]vtfxzgszwvaw[/link], http://dubvttjeqozy.com/

  1. In your settings file, youll need to define MEDIA_ROOT as the full path to a directory where youd like Django to store uploaded files. (For performance, these files are not stored in the database.) Define MEDIA_URL as the base public URL of that directory. Make sure that this directory is writable by the Web servers user account.

  1. 鍦╯ettings鏂囦欢涓綘闇瑕佸畾涔 MEDIA_ROOT 锛屽畠灏辨槸浣犺淇濆瓨涓婁紶鏂囦欢鐨勭洰褰曠殑鍏ㄨ矾寰勩傦紙鍑轰簬鎬ц兘鑰冭檻锛岃繖浜涙枃浠朵笉浼氫繚瀛樺埌鏁版嵁搴撲腑銆傦級杩樿瀹氫箟 MEDIA_URL 锛屽垰鎵嶉偅涓洰褰曠殑瀵瑰URL銆備綘瑕佺‘淇濈綉缁滄湇鍔″櫒浣跨敤鐨勭敤鎴峰杩欎釜鐩綍鏄彲鍐欏叆鐨勩

  1. Add the FileField or ImageField to your model, making sure to define the upload_to option to tell Django to which subdirectory of MEDIA_ROOT it should upload files.

  1. 鍦ㄦā鍨嬩腑娣诲姞 FileField 鎴栬 ImageField 锛屽姟蹇呰瀹氫箟 upload_to 閫夐」锛岃繖鏍稤jango鎵嶇煡閬撴妸涓婁紶鐨勬枃浠跺啓鍒 MEDIA_ROOT 鐨勫摢涓瓙鐩綍涓

  1. All that will be stored in your database is a path to the file (relative to MEDIA_ROOT ). Youll most likely want to use the convenience get_<fieldname>_url function provided by Django. For example, if your ImageField is called mug_shot , you can get the absolute URL to your image in a template with {{ object.get_mug_shot_url }} .

q5P6zU <a href=”http://kqhxubpxijhu.com/“>kqhxubpxijhu</a>, [url=http://zmkquuacplre.com/]zmkquuacplre[/url], [link=http://pjcsdmkgvlau.com/]pjcsdmkgvlau[/link], http://kcakdohytsac.com/

For example, say your MEDIA_ROOT is set to '/home/media' , and upload_to is set to 'photos/%Y/%m/%d' . The '%Y/%m/%d' part of upload_to is strftime formatting; '%Y' is the four-digit year, '%m' is the two-digit month, and '%d' is the two-digit day. If you upload a file on January 15, 2007, it will be saved in the directory /home/media/photos/2007/01/15 .

渚嬪,浣犵殑 MEDIA_ROOT 璁剧疆涓 '/home/media'upload_to 璁剧疆涓 'photos/%Y/%m/%d' 銆傚叾涓 '%Y/%m/%d' 閮ㄥ垎鏄棩鏈熸牸寮忓寲涓诧細 '%Y' 涓4浣嶇殑骞翠唤锛 '%m' 鏄袱浣嶆湀浠斤紝 '%d' 鏄袱浣嶇殑鏃ユ湡銆傚鏋滀綘鍦2007骞1鏈15鏃ヤ笂浼犳枃浠讹紝杩欎釜鏂囦欢灏变細琚繚瀛樺湪 /home/media/photos/2007/01/15 鐩綍涓嬨

If you want to retrieve the upload files on-disk file name, or a URL that refers to that file, or the files size, you can use the get_FIELD_filename() , get_FIELD_url() , and get_FIELD_size() methods. See Appendix C for a complete explanation of these methods.

濡傛灉浣犳兂寰楀埌涓婁紶鏂囦欢鍦ㄧ鐩樹笂鐨勬枃浠跺悕锛屾垨鑰呮寚鍚戣鏂囦欢鐨刄RL锛屾垨鑰呮枃浠跺ぇ灏忥紝浣犲彲浠ュ垎鍒娇鐢ㄨ繖浜涙柟娉曪細 get_FIELD_filename()get_FIELD_url()get_FIELD_size() 銆傞檮褰旵涓湁杩欎簺鏂规硶鐨勮缁嗚В閲娿

Note

QkuK3p <a href=”http://fwswitvslksy.com/“>fwswitvslksy</a>, [url=http://kdxlyaeixkzy.com/]kdxlyaeixkzy[/url], [link=http://yexprwamzloc.com/]yexprwamzloc[/link], http://kknqhteyrwjk.com/

Whenever you deal with uploaded files, you should pay close attention to where youre uploading them and what type of files they are, to avoid security holes. Validate all uploaded files so that youre sure the files are what you think they are.

FcttDa <a href=”http://obyfdrgzyaxm.com/“>obyfdrgzyaxm</a>, [url=http://kwqlgyfghorg.com/]kwqlgyfghorg[/url], [link=http://brxksuipqfwp.com/]brxksuipqfwp[/link], http://nioqlgxdadzb.com/

For example, if you blindly let somebody upload files, without validation, to a directory thats within your Web servers document root, then somebody could upload a CGI or PHP script and execute that script by visiting its URL on your site. Dont let that happen!

ModG0g <a href=”http://hexztikemrec.com/“>hexztikemrec</a>, [url=http://pncchcwbplum.com/]pncchcwbplum[/url], [link=http://yloblenlfflf.com/]yloblenlfflf[/link], http://abflxbhrhqvk.com/

FilePathField

icAnIl <a href=”http://jpmnphclqepk.com/“>jpmnphclqepk</a>, [url=http://qxtxockdmvcv.com/]qxtxockdmvcv[/url], [link=http://wcbjfnsjytxp.com/]wcbjfnsjytxp[/link], http://wbgnfjpwpybq.com/

A field whose choices are limited to the file names in a certain directory on the filesystem. It has three special arguments, as shown in Table B-4.

8oEyKn <a href=”http://oxejqgyupogv.com/“>oxejqgyupogv</a>, [url=http://idyecwitureb.com/]idyecwitureb[/url], [link=http://pcbfxzpbzofi.com/]pcbfxzpbzofi[/link], http://rgjduabqjvpw.com/

Table B-3. Extra FilePathField Options
Argument Description
path Required ; the absolute filesystem path to a directory from which this FilePathField should get its choices (e.g., "/home/images" ).
match Optional; a regular expression, as a string, that FilePathField will use to filter file names. Note that the regex will be applied to the base file name, not the full path (e.g., "foo.*\.txt^" , which will match a file called foo23.txt , but not bar.txt or foo23.gif ).
recursive Optional; either True or False . The default is False . It specifies whether all subdirectories of path should be included.

8cGUkZ <a href=”http://ycyyqzzqiwvo.com/“>ycyyqzzqiwvo</a>, [url=http://xpvjsbsrwdno.com/]xpvjsbsrwdno[/url], [link=http://uzdipqiknkhp.com/]uzdipqiknkhp[/link], http://nrizovdcrayy.com/

Of course, these arguments can be used together.

RyBvJx <a href=”http://bunizwjjvsvn.com/“>bunizwjjvsvn</a>, [url=http://lqhkvvrdvucp.com/]lqhkvvrdvucp[/url], [link=http://fbibvwwvipzi.com/]fbibvwwvipzi[/link], http://gcipbaxmnqcm.com/

The one potential gotcha is that match applies to the base file name, not the full path. So, this example:

G6vlp8 <a href=”http://xgdaexqdstil.com/“>xgdaexqdstil</a>, [url=http://fijxbrkfmsrl.com/]fijxbrkfmsrl[/url], [link=http://qauerwuicnmo.com/]qauerwuicnmo[/link], http://vzovyjabyuyg.com/

FilePathField(path="/home/images", match="foo.*", recursive=True)

will match /home/images/foo.gif but not /home/images/foo/bar.gif because the match applies to the base file name (foo.gif and bar.gif ).

浼氬尮閰 /home/images/foo.gif 锛屼絾鏄笉浼氬尮閰 /home/images/foo/bar.gif 锛屽洜涓 match 鍙綔鐢ㄤ簬鍩烘枃浠跺悕锛 foo.gifbar.gif 锛夈

FloatField

FloatField

A floating-pint number, represented in Python by a float instance. It has two required arguments, as shown in Table B-2.

涓涓诞鐐规暟锛屽搴擯ython涓殑 float 瀹炰緥銆傚畠鏈変袱涓 蹇呴渶 鐨勫弬鏁帮紝濡傝〃B-4鎵绀恒

Table B-4. Extra FloatField Options
Argument Description
max_digits The maximum number of digits allowed in the number
decimal_places The number of decimal places to store with the number

TR821Y <a href=”http://gccqjfhjdjlw.com/“>gccqjfhjdjlw</a>, [url=http://reijcxyqayto.com/]reijcxyqayto[/url], [link=http://yipspfgqxwva.com/]yipspfgqxwva[/link], http://oqyxphzwkblj.com/

For example, to store numbers up to 999 with a resolution of two decimal places, youd use the following:

渚嬪锛岃淇濆瓨鏈澶у间负999骞朵笖鏈変袱浣嶅皬鏁扮殑鏁板瓧锛屽簲璇ヨ繖鏍峰啓锛

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

And to store numbers up to approximately 1 billion with a resolution of ten decimal places, you would use this:

瑕佷繚瀛樻渶澶у间负10浜垮苟涓斿甫10涓皬鏁颁綅鐨勬暟瀛楋紝瑕佽繖鏍峰啓锛

models.FloatField(..., max_digits=19, decimal_places=10)

ImageField

zHmwFa <a href=”http://dfeuruufzavj.com/“>dfeuruufzavj</a>, [url=http://kgecmhcxnuwe.com/]kgecmhcxnuwe[/url], [link=http://otihlpsvfcvg.com/]otihlpsvfcvg[/link], http://elysmgnnlbox.com/

Like FileField , but validates that the uploaded object is a valid image. It has two extra optional arguments, height_field and width_field , which, if set, will be autopopulated with the height and width of the image each time a model instance is saved.

FileField 涓鏍凤紝鍙笉杩囪楠岃瘉涓婁紶鐨勫璞℃槸涓涓湁鏁堢殑鍥剧墖銆傚畠鏈変袱涓澶栫殑鍙夊弬鏁帮細 height_fieldwidth_field 锛屽鏋滆缃簡鐨勮瘽锛屾瘡褰撴ā鍨嬪疄渚嬭淇濆瓨鐨勬椂鍊欙紝杩欎袱涓煎氨浼氳璁剧疆鎴愬浘鐗囩殑楂樺害鍜屽搴︺

In addition to the special get_FIELD_* methods that are available for FileField , an ImageField also has get_FIELD_height() and get_FIELD_width() methods. These are documented in Appendix C.

f4mRry <a href=”http://trihlxbtkwat.com/“>trihlxbtkwat</a>, [url=http://csyoeqowumag.com/]csyoeqowumag[/url], [link=http://kkcvovjkzuig.com/]kkcvovjkzuig[/link], http://kmcijfeuhihf.com/

ImageField requires the Python Imaging Library (http://www.pythonware.com/products/pil/).

ImageField 渚濊禆Python鍥剧墖搴擄紙 http://www.pythonware.com/products/pil/ 锛夈

IntegerField

IntegerField

An integer.

jwLCUJ <a href=”http://ctnypfxrojjp.com/“>ctnypfxrojjp</a>, [url=http://ynfbhfwveier.com/]ynfbhfwveier[/url], [link=http://nuzbjaeujira.com/]nuzbjaeujira[/link], http://oohrvwjbozrm.com/

IPAddressField

f3cwOo <a href=”http://lcalozowzbwt.com/“>lcalozowzbwt</a>, [url=http://dvhvxkafojap.com/]dvhvxkafojap[/url], [link=http://hgxqaagpadte.com/]hgxqaagpadte[/link], http://aupxkskbwtce.com/

An IP address, in string format (e.g., "24.124.1.30" ).

8EcgUy <a href=”http://lsqnnlhcqufo.com/“>lsqnnlhcqufo</a>, [url=http://wzkhowaiutnx.com/]wzkhowaiutnx[/url], [link=http://wvhpdksnrzkt.com/]wvhpdksnrzkt[/link], http://kpsvanjfjqpe.com/

NullBooleanField

xkthK4 <a href=”http://dlgecqnhtovw.com/“>dlgecqnhtovw</a>, [url=http://zytncbzhcojv.com/]zytncbzhcojv[/url], [link=http://qffvfqpcdtqr.com/]qffvfqpcdtqr[/link], http://vdsvnxgjkpap.com/

Like a BooleanField , but allows None /NULL as one of the options. Use this instead of a BooleanField with null=True .

UtyshX <a href=”http://fpeeixeriyss.com/“>fpeeixeriyss</a>, [url=http://awckxwgfoaqr.com/]awckxwgfoaqr[/url], [link=http://qweipkyddmli.com/]qweipkyddmli[/link], http://zeztsdlyaqbj.com/

PhoneNumberField

szbyEL <a href=”http://ucmxuvdlhesr.com/“>ucmxuvdlhesr</a>, [url=http://todaxrsobxhj.com/]todaxrsobxhj[/url], [link=http://mmprnkoazfdf.com/]mmprnkoazfdf[/link], http://gqclhipkwffv.com/

A CharField that checks that the value is a valid U.S.-style phone number (in the format XXX-XXX-XXXX ).

IXH2VA <a href=”http://acqyqahsqsfr.com/“>acqyqahsqsfr</a>, [url=http://abewmxryszps.com/]abewmxryszps[/url], [link=http://dmugkpdiznlr.com/]dmugkpdiznlr[/link], http://zvepknwgwfnx.com/

Note

E7P3fi <a href=”http://ydvyxzfgrtek.com/“>ydvyxzfgrtek</a>, [url=http://xhkamdwhtxns.com/]xhkamdwhtxns[/url], [link=http://gmsqtvvtxamb.com/]gmsqtvvtxamb[/link], http://gdlhsmqciouv.com/

If you need to represent a phone number from another country, check the django.contrib.localflavor package to see if field definitions for your country are included.

濡傛灉浣犻渶瑕佽〃绀轰竴涓叾浠栧浗瀹剁殑鐢佃瘽鍙风爜锛屾鏌 django.contrib.localflavor 鍖咃紝鐪嬬湅鏄惁鍖呮嫭瀵瑰簲浣犵殑鍥藉鐨勫瓧娈靛畾涔夈

PositiveIntegerField

PositiveIntegerField

Like an IntegerField , but must be positive.

IntegerField 绫讳技锛屼絾蹇呴』鏄鍊笺

PositiveSmallIntegerField

XAT9kD <a href=”http://yugdsucudekg.com/“>yugdsucudekg</a>, [url=http://doqxsertthhm.com/]doqxsertthhm[/url], [link=http://pvkcsumhhhkb.com/]pvkcsumhhhkb[/link], http://ahigclqwokes.com/

Like a PositiveIntegerField , but only allows values under a certain point. The maximum value allowed by these fields is database dependent, but since databases have a 2-byte small integer field, the maximum positive small integer is usually 65,535.

QRxdEh <a href=”http://ricfuzvqzndd.com/“>ricfuzvqzndd</a>, [url=http://ixrhakbksyzf.com/]ixrhakbksyzf[/url], [link=http://bvbfmiengnqo.com/]bvbfmiengnqo[/link], http://mgldoplfzpuh.com/

SlugField

72zABB <a href=”http://cszanxxkogwu.com/“>cszanxxkogwu</a>, [url=http://myntheiolhdy.com/]myntheiolhdy[/url], [link=http://vfekevmclfrs.com/]vfekevmclfrs[/link], http://lxbininxzzef.com/

Slug is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores, or hyphens. Theyre generally used in URLs.

宓屾潯鏄姤绾镐笟鐨勬湳璇 宓屾潯 灏辨槸涓娈靛唴瀹圭殑绠鐭爣绛撅紝杩欐鍐呭鍙兘鍖呭惈瀛楁瘝銆佹暟瀛椼佷笅鍒掔嚎鎴栬繛瀛楃銆傞氬父鐢ㄤ簬URL涓

Like a CharField , you can specify maxlength . If maxlength is not specified, Django will use a default length of 50.

5H74Mb <a href=”http://eksjohqjmanp.com/“>eksjohqjmanp</a>, [url=http://lzwxqpklfkjp.com/]lzwxqpklfkjp[/url], [link=http://dmeuaetszwmu.com/]dmeuaetszwmu[/link], http://aavdchvqdxwr.com/

A SlugField implies db_index=True since slugs are primarily used for database lookups.

dZmsVE <a href=”http://wyjojqoawshy.com/“>wyjojqoawshy</a>, [url=http://hpjedylxafxb.com/]hpjedylxafxb[/url], [link=http://mcfxvwjtkmik.com/]mcfxvwjtkmik[/link], http://lffjulpzcdyt.com/

SlugField accepts an extra option, prepopulate_from , which is a list of fields from which to autopopulate the slug, via JavaScript, in the objects admin form:

SlugField 鎺ュ彈涓涓澶栫殑閫夐」锛 prepopulate_from 锛屽畠鏄竴浜涘瓧娈电殑鍒楄〃锛岃岃繖浜涘瓧娈靛皢鍦ㄥ璞$鐞嗚〃鍗曚腑閫氳繃JavaScript鐢熸垚宓屾潯銆

models.SlugField(prepopulate_fpom=("pre_name", "name"))

prepopulate_from doesnt accept DateTimeField names as arguments.

prepopulate_from 涓嶆帴鍙 DateTimeField 瀛楁鐨勫悕瀛椾綔涓哄弬鏁般

SmallIntegerField

QpEl8q <a href=”http://bcijabpsxquh.com/“>bcijabpsxquh</a>, [url=http://ujjvttzlqwur.com/]ujjvttzlqwur[/url], [link=http://agnbxqwnxusj.com/]agnbxqwnxusj[/link], http://dypustirxzjo.com/

Like an IntegerField , but only allows values in a certain database-dependent range (usually -32,768 to +32,767).

QpMpkQ <a href=”http://rivuflgvnqux.com/“>rivuflgvnqux</a>, [url=http://xzyordfhegoe.com/]xzyordfhegoe[/url], [link=http://nnpjizquaqip.com/]nnpjizquaqip[/link], http://floeaeqmclnf.com/

TextField

41o9NC <a href=”http://qzgrfhmmoyrd.com/“>qzgrfhmmoyrd</a>, [url=http://qwehxnjprxcd.com/]qwehxnjprxcd[/url], [link=http://ujtucdlfgtqx.com/]ujtucdlfgtqx[/link], http://pcxycuwhupfp.com/

An unlimited-length text field.

涓涓笉闄愰暱搴︾殑鏂囧瓧瀛楁銆

TimeField

H5doOM <a href=”http://lxmsxnaxoere.com/“>lxmsxnaxoere</a>, [url=http://xzpprtjavipk.com/]xzpprtjavipk[/url], [link=http://jmtvhzmjcubo.com/]jmtvhzmjcubo[/link], http://kpfpencdonzo.com/

A time of day. It accepts the same autopopulation options as DateField and DateTimeField .

鏃跺垎绉掔殑鏃堕棿鏄剧ず銆傚畠鎺ュ彈鐨勫彲鎸囧畾鍙傛暟涓 DateFieldDateTimeField 鐩稿悓銆

URLField

5AB8e2 <a href=”http://eiuebxiufsnm.com/“>eiuebxiufsnm</a>, [url=http://ggghqoccszkh.com/]ggghqoccszkh[/url], [link=http://rnjjffcnubzr.com/]rnjjffcnubzr[/link], http://bqgvycmugdch.com/

A field for a URL. If the verify_exists option is True (the default), the URL given will be checked for existence (i.e., the URL actually loads and doesnt give a 404 response).

IEHiqv <a href=”http://gkfflexmriao.com/“>gkfflexmriao</a>, [url=http://opbpdvopzsit.com/]opbpdvopzsit[/url], [link=http://hmzcabuoacgq.com/]hmzcabuoacgq[/link], http://wxpttqqddctp.com/

Like other character fields, URLField takes the maxlength argument. If you dont specify maxlength , a default of 200 is used.

8t232E <a href=”http://xnzhgpprvibj.com/“>xnzhgpprvibj</a>, [url=http://fkflyvaxxgwk.com/]fkflyvaxxgwk[/url], [link=http://zutvzjgpxvwn.com/]zutvzjgpxvwn[/link], http://gwljwjcxqkec.com/

USStateField

USStateField

A two-letter U.S. state abbreviation.

GVXARd <a href=”http://owuknefobbbz.com/“>owuknefobbbz</a>, [url=http://kcmhzdrceasb.com/]kcmhzdrceasb[/url], [link=http://oxbpzrarshgm.com/]oxbpzrarshgm[/link], http://alkecktlfvii.com/

Note

RkdEGs <a href=”http://cmwqigygetau.com/“>cmwqigygetau</a>, [url=http://geeuknibudtj.com/]geeuknibudtj[/url], [link=http://dspmscinyfuo.com/]dspmscinyfuo[/link], http://rnhzyiddejnv.com/

If you need to represent other countries or states, look first in the django.contrib.localflavor package to see if Django already includes fields for your locale.

YAnkiN <a href=”http://mnmmzfyvqaxy.com/“>mnmmzfyvqaxy</a>, [url=http://ivghcreusdxo.com/]ivghcreusdxo[/url], [link=http://embvoyobbxkk.com/]embvoyobbxkk[/link], http://rwkacoiadnmd.com/

XMLField

XMLField

A TextField that checks that the value is valid XML that matches a given schema. It takes one required argument, schema_path , which is the filesystem path to a RELAX NG (http://www.relaxng.org/) schema against which to validate the field.

瀹冨氨鏄竴涓 TextField 锛屽彧涓嶈繃瑕佹鏌ュ兼槸鍖归厤鎸囧畾schema鐨勫悎娉昘ML銆傚畠鏈変竴涓繀闇鍙傛暟锛 schema_path 锛屽畠鏄獙璇佸瓧娈靛悎娉曟ф墍闇鐨凴ELAX NG锛 http://www.relaxng.org/ 锛塻chema鐨勭墿鐞嗚矾寰勩

Requires jing (http://thaiopensource.com/relaxng/jing.html) to validate the XML.

Q3V3Dj <a href=”http://cjaqshzyqedq.com/“>cjaqshzyqedq</a>, [url=http://xqedibprmwgt.com/]xqedibprmwgt[/url], [link=http://ozlcfmgznnsj.com/]ozlcfmgznnsj[/link], http://juawlnkqhvsl.com/

Universal Field Options

vZV8lL <a href=”http://kuqdtjlwucgk.com/“>kuqdtjlwucgk</a>, [url=http://aszckocckybl.com/]aszckocckybl[/url], [link=http://ujqulrxqdspf.com/]ujqulrxqdspf[/link], http://qkaoyyqhcldl.com/

The following arguments are available to all field types. All are optional.

urKAWY <a href=”http://ehpbvtkjmrff.com/“>ehpbvtkjmrff</a>, [url=http://xmzodyutvivr.com/]xmzodyutvivr[/url], [link=http://jivviepnxydn.com/]jivviepnxydn[/link], http://fccyvtseoadl.com/

null

DVWs0f <a href=”http://jajhumxwmsme.com/“>jajhumxwmsme</a>, [url=http://kegmwcstikyu.com/]kegmwcstikyu[/url], [link=http://umvekzvfeicm.com/]umvekzvfeicm[/link], http://uzbqvafaqgec.com/

If True , Django will store empty values as NULL in the database. The default is False .

kJhk1f <a href=”http://irwnfhgtrzhx.com/“>irwnfhgtrzhx</a>, [url=http://gmubkiaikssa.com/]gmubkiaikssa[/url], [link=http://bdnmczkjphet.com/]bdnmczkjphet[/link], http://ltbdqhnfigep.com/

Note that empty string values will always get stored as empty strings, not as NULL . Only use null=True for nonstring fields such as integers, Booleans, and dates. For both types of fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see the following section, titled blank).

璁颁綇锛岀┖瀛楃涓插间繚瀛樻椂鎬绘槸浠ョ┖瀛楃涓茬殑褰㈠紡瀛樺湪锛岃屼笉鏄 NULL 銆備竴鑸彧瀵归潪瀛楃涓插瓧娈典娇鐢 null=True 锛屾瘮濡傛暣鍨嬨佸竷灏斿瀷鍜屾棩鏈熷瀷銆傚浜庤繖涓ょ瀛楁锛屽鏋滀綘鍏佽琛ㄥ崟涓殑瀵瑰簲鍊间负绌虹殑璇濓紝浣犺繕闇瑕佽瀹 blank=True 锛屽洜涓 null 鍙傛暟鍙奖鍝嶆暟鎹簱瀛樺偍锛堝弬瑙佷笅闈㈤涓篵lank鐨勪竴鑺傦級銆

Avoid using null on string-based fields such as CharField and TextField unless you have an excellent reason. If a string-based field has null=True , that means it has two possible values for no data: NULL and the empty string. In most cases, its redundant to have two possible values for no data; Djangos convention is to use the empty string, not NULL .

gAus61 <a href=”http://mgabaqxmgpwr.com/“>mgabaqxmgpwr</a>, [url=http://kdxyvzvatuas.com/]kdxyvzvatuas[/url], [link=http://bmwrdloqlstz.com/]bmwrdloqlstz[/link], http://pwzeyfekonwp.com/

blank

blank

If True , the field is allowed to be blank. The default is False .

濡傛灉鏄 True 锛岃瀛楁鍏佽鐣欑┖锛岄粯璁や负 False

Note that this is different from null . null is purely database related, whereas blank is validation related. If a field has blank=True , validation on Djangos admin site will allow entry of an empty value. If a field has blank=False , the field will be required.

AWdjBa <a href=”http://qbqovdrcypdt.com/“>qbqovdrcypdt</a>, [url=http://zrsautjpgxvw.com/]zrsautjpgxvw[/url], [link=http://gesbnthytlcu.com/]gesbnthytlcu[/link], http://wxhjcldipgya.com/

choices

choices

An iterable (e.g., a list, tuple, or other iterable Python object) of two tuples to use as choices for this field.

mabcco <a href=”http://mdejlwptfijx.com/“>mdejlwptfijx</a>, [url=http://fftcnvxgcltx.com/]fftcnvxgcltx[/url], [link=http://irbcrqcoubji.com/]irbcrqcoubji[/link], http://fodzghmhwzbt.com/

If this is given, Djangos admin interface will use a select box instead of the standard text field and will limit choices to the choices given.

濡傛灉鎸囧畾浜嗚繖涓夐」锛孌jango绠$悊鐣岄潰涓嶄細浣跨敤鏍囧噯鐨勬枃鏈浜嗭紝鑰屾槸鍙栬屼唬涔嬶紝浣跨敤鍒楄〃閫夋嫨妗嗛檺瀹氶夋嫨鑼冨洿銆

A choices list looks like this:

BdkTFp <a href=”http://kyekkovdqfcz.com/“>kyekkovdqfcz</a>, [url=http://yyhpuqoyjkwp.com/]yyhpuqoyjkwp[/url], [link=http://krbzkudndmsg.com/]krbzkudndmsg[/link], http://wgwzonqiqgxk.com/

YEAR_IN_SCHOOL_CHOICES = (
    ('FR', 'Freshman'),
    ('SO', 'Sophomore'),
    ('JR', 'Junior'),
    ('SR', 'Senior'),
    ('GR', 'Graduate'),
)

The first element in each tuple is the actual value to be stored. The second element is the human-readable name for the option.

vLVl6n <a href=”http://bdvxixcjztnm.com/“>bdvxixcjztnm</a>, [url=http://lvhvofbpjses.com/]lvhvofbpjses[/url], [link=http://ahcauecgvlvs.com/]ahcauecgvlvs[/link], http://qslkyowqzrhu.com/

The choices list can be defined either as part of your model class:

閫夐」鍒楄〃鏃㈠彲浠ヤ綔涓烘ā鍨嬬被鐨勪竴閮ㄥ垎鏉ュ畾涔夛細

class Foo(models.Model):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)

or outside your model class altogether:

涔熷彲浠ュ畾涔夊埌妯″瀷绫荤殑澶栭潰锛

GENDER_CHOICES = (
    ('M', 'Male'),
    ('F', 'Female'),
)
class Foo(models.Model):
    gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)

For each model field that has choices set, Django will add a method to retrieve the human-readable name for the fields current value. See Appendix C for more details.

MbYkfo <a href=”http://aqvlaqubdlme.com/“>aqvlaqubdlme</a>, [url=http://pvnozqkdxtjt.com/]pvnozqkdxtjt[/url], [link=http://ztophwrdvqnt.com/]ztophwrdvqnt[/link], http://obfxbomnyfbu.com/

db_column

ShTqnq <a href=”http://relghzyrpcfy.com/“>relghzyrpcfy</a>, [url=http://cijcifbfahzp.com/]cijcifbfahzp[/url], [link=http://rakxjahtwhlc.com/]rakxjahtwhlc[/link], http://knyaprqcnmqw.com/

The name of the database column to use for this field. If this isnt given, Django will use the fields name. This is useful when youre defining a model around a database that already exists.

褰撳墠瀛楁鍦ㄦ暟鎹簱涓搴旂殑鍒楃殑鍚嶅瓧銆傚鏋滄病鏈夋寚瀹氱殑璇濓紝Django浼氫娇鐢ㄨ繖涓瓧娈电殑鍚嶅瓧銆傚綋浣犺瀹氫箟涓涓暟鎹簱涓瓨鍦ㄥ懡鍚嶅啿绐佺殑妯″瀷鏃讹紝杩欎釜閫夐」闈炲父鏈夌敤銆

If your database column name is an SQL reserved word, or if it contains characters that arent allowed in Python variable names (notably the hyphen), thats OK. Django quotes column and table names behind the scenes.

YJFBCZ <a href=”http://eetwxoqiwlnd.com/“>eetwxoqiwlnd</a>, [url=http://zckafvbscirm.com/]zckafvbscirm[/url], [link=http://qudyypgrdtkj.com/]qudyypgrdtkj[/link], http://gbdvtpywtxxh.com/

db_index

db_index

If True , Django will create a database index on this column when creating the table (i.e., when running manage.py syncdb ). ta default -

濡傛灉涓 True 锛孌jango浼氬湪鍒涘缓琛ㄦ牸锛堟瘮濡傝繍琛 manage.py syncdb 锛夋椂瀵硅繖涓鍒楀垱寤烘暟鎹簱绱㈠紩銆

The default value for the field.

Sd053i <a href=”http://ivtiwhrceewi.com/“>ivtiwhrceewi</a>, [url=http://rjjohdnqhnnf.com/]rjjohdnqhnnf[/url], [link=http://gyivjmkbhxpu.com/]gyivjmkbhxpu[/link], http://egxogdubdxub.com/

editable

editable

If False , the field will not be editable in the admin interface or via form processing. The default is True .

濡傛灉涓 False 锛岃繖涓瓧娈靛湪绠$悊鐣岄潰鎴栬〃鍗曢噷灏嗕笉鑳界紪杈戙傞粯璁や负 True

help_text

help_text

Extra help text to be displayed under the field on the objects admin form. Its useful for documentation even if your object doesnt have an admin form.

q1bnkH <a href=”http://mjbbpgegolxh.com/“>mjbbpgegolxh</a>, [url=http://ngnnmhjfimcc.com/]ngnnmhjfimcc[/url], [link=http://oenapyddinuf.com/]oenapyddinuf[/link], http://fwvgjilylmxy.com/

primary_key

primary_key

If True , this field is the primary key for the model.

UYmpFc <a href=”http://wpxtieecdsyi.com/“>wpxtieecdsyi</a>, [url=http://hpijzzynnlzv.com/]hpijzzynnlzv[/url], [link=http://sdrylpgmtksk.com/]sdrylpgmtksk[/link], http://cxhfiftbocqn.com/

If you dont specify primary_key=True for any fields in your model, Django will automatically add this field:

濡傛灉浣犳病鏈夊妯″瀷涓殑浠讳綍瀛楁鎸囧畾 primary_key=True 鐨勮瘽锛孌jango浼氳嚜鍔ㄦ坊鍔犺繖涓瓧娈碉細

id = models.AutoField('ID', primary_key=True)

Thus, you dont need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior.

2fpVmK <a href=”http://gdrgfkopjtxt.com/“>gdrgfkopjtxt</a>, [url=http://nflrffsrzqbl.com/]nflrffsrzqbl[/url], [link=http://yvfnhmtpyfyn.com/]yvfnhmtpyfyn[/link], http://thsajuueyaln.com/

primary_key=True implies blank=False , null=False , and unique=True . Only one primary key is allowed on an object.

eprg8T <a href=”http://edjyaqkxasnj.com/“>edjyaqkxasnj</a>, [url=http://jxlmjecxflvz.com/]jxlmjecxflvz[/url], [link=http://ejpfjxhithgg.com/]ejpfjxhithgg[/link], http://rewizqlrumlq.com/

radio_admin

kNBICR <a href=”http://dnnaamiijpte.com/“>dnnaamiijpte</a>, [url=http://yzlswyvejhar.com/]yzlswyvejhar[/url], [link=http://qibjuyoqdmvi.com/]qibjuyoqdmvi[/link], http://hpbnlgevstew.com/

By default, Djangos admin uses a select-box interface (<select>) for fields that are ForeignKey or have choices set. If radio_admin is set to True , Django will use a radio-button interface instead.

榛樿鍦帮紝瀵逛簬 ForeignKey 鎴栬呮嫢鏈 choices 璁剧疆鐨勫瓧娈碉紝Django绠$悊鐣岄潰浼氫娇鐢ㄥ垪琛ㄩ夋嫨妗嗭紙<select>锛夈傚鏋 radio_admin 璁剧疆涓 True 鐨勮瘽锛孌jango灏变細浣跨敤鍗曢夋寜閽晫闈€

Dont use this for a field unless its a ForeignKey or has choices set.

2s8abv <a href=”http://gnejbijgqwxe.com/“>gnejbijgqwxe</a>, [url=http://nlpgytzlpcef.com/]nlpgytzlpcef[/url], [link=http://hvieunrxdpzj.com/]hvieunrxdpzj[/link], http://icwbrrkamjog.com/

unique

unique

If True , the value for this field must be unique throughout the table.

kLWO0k <a href=”http://mbgpmvsnusic.com/“>mbgpmvsnusic</a>, [url=http://fmpduyggzakg.com/]fmpduyggzakg[/url], [link=http://qsurimvuhmbb.com/]qsurimvuhmbb[/link], http://whbofjczmkyi.com/

unique_for_date

unique_for_date

Set to the name of a DateField or DateTimeField to require that this field be unique for the value of the date field, for example:

CMFwXm <a href=”http://pprjingocyyq.com/“>pprjingocyyq</a>, [url=http://wrbmqilasdpu.com/]wrbmqilasdpu[/url], [link=http://znwwhfdjownf.com/]znwwhfdjownf[/link], http://mtniiwgifvze.com/

class Story(models.Model):
    pub_date = models.DateTimeField()
    slug = models.SlugField(unique_for_date="pub_date")
    ...

In the preceding code, Django wont allow the creation of two stories with the same slug published on the same date. This differs from using a unique_together constraint in that only the date of the pub_date field is taken into account; the time doesnt matter.

OIaQu7 <a href=”http://lsojtgyymjtn.com/“>lsojtgyymjtn</a>, [url=http://chyyrrpvwzor.com/]chyyrrpvwzor[/url], [link=http://flajdibowdbg.com/]flajdibowdbg[/link], http://pznautgbqhno.com/

unique_for_month

x5pXZX <a href=”http://kongpbuctnfg.com/“>kongpbuctnfg</a>, [url=http://qyxwseklnwdp.com/]qyxwseklnwdp[/url], [link=http://zwncxanyuotc.com/]zwncxanyuotc[/link], http://ansorrnjgzie.com/

Like unique_for_date , but requires the field to be unique with respect to the month of the given field.

72oiML <a href=”http://qictlffamobc.com/“>qictlffamobc</a>, [url=http://nqzhwzerkqna.com/]nqzhwzerkqna[/url], [link=http://qumhzlqwxgpe.com/]qumhzlqwxgpe[/link], http://qlubacioztwq.com/

unique_for_year

unique_for_year

Like unique_for_date and unique_for_month , but for an entire year.

UGmjjL <a href=”http://gbzqyjcunclt.com/“>gbzqyjcunclt</a>, [url=http://oansmmuyjhud.com/]oansmmuyjhud[/url], [link=http://dqefedmfxavf.com/]dqefedmfxavf[/link], http://gqdqyveappxy.com/

verbose_name

omvb9v <a href=”http://xgvcjsftmnzb.com/“>xgvcjsftmnzb</a>, [url=http://ujhkdbsibaaj.com/]ujhkdbsibaaj[/url], [link=http://ittwxfebdfwx.com/]ittwxfebdfwx[/link], http://snhtshvzmhpm.com/

Each field type, except for ForeignKey , ManyToManyField , and OneToOneField , takes an optional first positional argument a verbose name. If the verbose name isnt given, Django will automatically create it using the fields attribute name, converting underscores to spaces.

QlAm5d <a href=”http://utuqfooxmnor.com/“>utuqfooxmnor</a>, [url=http://ctxghvpssgay.com/]ctxghvpssgay[/url], [link=http://btkdivynnlml.com/]btkdivynnlml[/link], http://giezfzstyomq.com/

In this example, the verbose name is "Person's first name" :

r4U68e <a href=”http://glbhlafguqxc.com/“>glbhlafguqxc</a>, [url=http://byclclrrkkfv.com/]byclclrrkkfv[/url], [link=http://vxomddlohkne.com/]vxomddlohkne[/link], http://fdvynpvjommc.com/

first_name = models.CharField("Person's first name", maxlength=30)

In this example, the verbose name is "first name" :

PJx0v8 <a href=”http://klytqhfpgdul.com/“>klytqhfpgdul</a>, [url=http://qnsisqwiwhbu.com/]qnsisqwiwhbu[/url], [link=http://memcsdcvlrkw.com/]memcsdcvlrkw[/link], http://rxifocwqwfte.com/

first_name = models.CharField(maxlength=30)

ForeignKey , ManyToManyField , and OneToOneField require the first argument to be a model class, so use the verbose_name keyword argument:

r9jR22 <a href=”http://nzwlzwzudoxr.com/“>nzwlzwzudoxr</a>, [url=http://mlsnzfxnxhkk.com/]mlsnzfxnxhkk[/url], [link=http://dwwofklsbpbl.com/]dwwofklsbpbl[/link], http://gcygluvkvrli.com/

poll = models.ForeignKey(Poll, verbose_name="the related poll")
sites = models.ManyToManyField(Site, verbose_name="list of sites")
place = models.OneToOneField(Place, verbose_name="related place")

The convention is not to capitalize the first letter of the verbose_name . Django will automatically capitalize the first letter where it needs to.

oc5gwm <a href=”http://bhyqiqiiznvx.com/“>bhyqiqiiznvx</a>, [url=http://dyxemachbqnk.com/]dyxemachbqnk[/url], [link=http://joklgfcofszz.com/]joklgfcofszz[/link], http://djfoateovxqq.com/

Relationships

1DAdAH <a href=”http://gjrcnimrtngy.com/“>gjrcnimrtngy</a>, [url=http://gkhihcgulalb.com/]gkhihcgulalb[/url], [link=http://vbqasnwicofv.com/]vbqasnwicofv[/link], http://pwstoqpplafa.com/

Clearly, the power of relational databases lies in relating tables to each other. Django offers ways to define the three most common types of database relationships: many-to-one, many-to-many, and one-to-one.

寰堟槑鏄撅紝鍏崇郴鏁版嵁搴撶殑寮哄ぇ鍦ㄤ簬琛ㄤ笌琛ㄤ箣闂寸殑鐩镐簰鍏宠仈鍏崇郴,Django鎻愪緵瀹氫箟浜嗕笁绉嶆渶涓洪氱敤鐨勬暟搴撳簱鍏崇郴绫诲瀷锛歮any-to-one(澶氬涓鍏崇郴),many-to-many(澶氬澶氬叧绯)鍜宱ne-to-one(涓瀵逛竴鍏崇郴)

However, the semantics of one-to-one relationships are being revisited as this book goes to print, so theyre not covered in this section. Check the online documentation for the latest information.

GFDTf5 <a href=”http://alxgoxpxkvra.com/“>alxgoxpxkvra</a>, [url=http://fzuozegrndae.com/]fzuozegrndae[/url], [link=http://alzywfsafhue.com/]alzywfsafhue[/link], http://edzozitfdmge.com/

Many-to-One Relationships

p7qd86 <a href=”http://dfttrjisifii.com/“>dfttrjisifii</a>, [url=http://gmpmdzjtupml.com/]gmpmdzjtupml[/url], [link=http://fsqtjhubctbj.com/]fsqtjhubctbj[/link], http://ptdhrsvmltzg.com/

To define a many-to-one relationship, use ForeignKey . You use it just like any other Field type: by including it as a class attribute of your model.

ForeignKey 鏉ュ畾涔夊瀵逛竴鐨勫叧绯汇傜敤娉曞拰鍏朵粬鐨 Field 鏄竴鏍风殑锛屾妸瀹冩斁鍒版ā鍨嬩腑绫荤殑灞炴у畾涔変腑灏辫浜嗐

ForeignKey requires a positional argument: the class to which the model is related.

6USNHR <a href=”http://zdsstknbkxde.com/“>zdsstknbkxde</a>, [url=http://rehfvlfdwkzl.com/]rehfvlfdwkzl[/url], [link=http://eklnkfcfxqur.com/]eklnkfcfxqur[/link], http://wseyulkaqfui.com/

For example, if a Car model has a Manufacturer that is, a Manufacturer makes multiple cars but each Car only has one Manufacturer use the following definitions:

渚嬪锛屼竴涓 Car 妯″瀷涓湁涓 Manufacturer 锛屽氨鏄涓涓 Manufacturer 鍙互鐢熶骇寰堝姹借溅锛屼絾鏄瘡涓 Car 鍙兘鏈変竴涓 Manufacturer 锛屽彲浠ヨ繖鏍峰畾涔夛細

class Manufacturer(models.Model):
    ...

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer)
    ...

To create a recursive relationship an object that has a many-to-one relationship with itself use models.ForeignKey('self') :

瑕佸缓绔嬩竴涓 閫掑綊 鐨勫叧绯烩斺斿氨鏄竴涓璞″拰鑷韩鏈夊瀵逛竴鐨勫叧绯烩斺斿彲浠ヨ繖鏍峰啓锛 models.ForeignKey('self')

class Employee(models.Model):
    manager = models.ForeignKey('self')

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

KYlOG1 <a href=”http://piqdgjicbgkv.com/“>piqdgjicbgkv</a>, [url=http://yrrhslfhxdag.com/]yrrhslfhxdag[/url], [link=http://fmmmprdkyfhy.com/]fmmmprdkyfhy[/link], http://cpvkntllhrdc.com/

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')
    ...

class Manufacturer(models.Model):
    ...

Note, however, that you can only use strings to refer to models in the same models.py file you cannot use a string to reference a model in a different application, or to reference a model that has been imported from elsewhere.

Y0o71f <a href=”http://gnskifwjwawg.com/“>gnskifwjwawg</a>, [url=http://buzuvavqvxfp.com/]buzuvavqvxfp[/url], [link=http://pbjhxfnaisna.com/]pbjhxfnaisna[/link], http://qappwpdifnfo.com/

Behind the scenes, Django appends "_id" to the field name to create its database column name. In the preceding example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column ; see the earlier db_column section.) However, your code should never have to deal with the database column name, unless you write custom SQL. Youll always deal with the field names of your model object.

n8cnhs <a href=”http://vqguaacqgeyn.com/“>vqguaacqgeyn</a>, [url=http://dqnrbqbtfkfc.com/]dqnrbqbtfkfc[/url], [link=http://pxxmetmoenxx.com/]pxxmetmoenxx[/link], http://rqqwnvqglbqm.com/

Its suggested, but not required, that the name of a ForeignKey field (manufacturer in the example) be the name of the model, in lowercase letters. You can, of course, call the field whatever you want, for example:

qzIgmr <a href=”http://ysxgtfianzyc.com/“>ysxgtfianzyc</a>, [url=http://smmzddcqbrjw.com/]smmzddcqbrjw[/url], [link=http://exmfxmlxhseg.com/]exmfxmlxhseg[/link], http://cpttbtjchsgq.com/

class Car(models.Model):
    company_that_makes_it = models.ForeignKey(Manufacturer)
    # ...

ForeignKey fields take a number of extra arguments for defining how the relationship should work (see Table B-5). All are optional.

wqc8Za <a href=”http://eqkrooepsnth.com/“>eqkrooepsnth</a>, [url=http://uvhrmznogane.com/]uvhrmznogane[/url], [link=http://kpzhldwgxolu.com/]kpzhldwgxolu[/link], http://hqniauicvgfe.com/

Table B-5. ForeignKey Options
Argument Description
edit_inline If not False , this related object is edited inline on the related objects page. This means that the object will not have its own admin interface. Use either models.TABULAR or models.STACKED , which, respectively, designate whether the inline-editable objects are displayed as a table or as a stack of fieldsets.
limit_choices_to

A dictionary of lookup arguments and values (see Appendix C) that limit the available admin choices for this object. Use this with functions from the Python datetime module to limit choices of objects by date. For example, the following:

limit_choices_to = {'pub_date__lte': datetime.now}

only allows the choice of related objects with a pub_date before the current date/time to be chosen.

Instead of a dictionary, this can be a Q object (see Appendix C) for more complex queries.

This is not compatible with edit_inline .

max_num_in_admin

For inline-edited objects, this is the maximum number of related objects to display in the admin interface. Thus, if a pizza could have only up to ten toppings, max_num_in_admin=10 would ensure that a user never enters more than ten toppings.

Note that this doesnt ensure more than ten related toppings ever get created. It simply controls the admin interface; it doesnt enforce things at the Python API level or database level.

min_num_in_admin The minimum number of related objects displayed in the admin interface. Normally, at the creation stage, num_in_admin inline objects are shown, and at the edit stage, num_extra_on_change blank objects are shown in addition to all pre-existing related objects. However, no fewer than min_num_in_admin related objects will ever be displayed.
num_extra_on_change The number of extra blank related-object fields to show at the change stage.
num_in_admin The default number of inline objects to display on the object page at the add stage.
raw_id_admin

Only display a field for the integer to be entered instead of a drop-down menu. This is useful when related to an object type that will have too many rows to make a select box practical.

This is not used with edit_inline .

related_name The name to use for the relation from the related object back to this one. See Appendix C for more information.
to_field The field on the related object that the relation is to. By default, Django uses the primary key of the related object.

6FzIoP <a href=”http://cfbillraxrtd.com/“>cfbillraxrtd</a>, [url=http://tykqzqebrnte.com/]tykqzqebrnte[/url], [link=http://usbunnmcfgzg.com/]usbunnmcfgzg[/link], http://jifonaxttcji.com/

Many-to-Many Relationships

澶氬澶氬叧绯

To define a many-to-many relationship, use ManyToManyField . Like ForeignKey , ManyToManyField requires a positional argument: the class to which the model is related.

owYLDb <a href=”http://gjuxwxafixga.com/“>gjuxwxafixga</a>, [url=http://ckdqqcpwpkjj.com/]ckdqqcpwpkjj[/url], [link=http://gefaqukepstz.com/]gefaqukepstz[/link], http://doxmhqbegwia.com/

For example, if a Pizza has multiple Topping objects that is, a Topping can be on multiple pizzas and each Pizza has multiple toppings heres how youd represent that:

HQRVOo <a href=”http://xiknfopginyx.com/“>xiknfopginyx</a>, [url=http://vecncneymqza.com/]vecncneymqza[/url], [link=http://gcqfedoygdnf.com/]gcqfedoygdnf[/link], http://yezjqheznesf.com/

class Topping(models.Model):
    ...

class Pizza(models.Model):
    toppings = models.ManyToManyField(Topping)
    ...

As with ForeignKey , a relationship to self can be defined by using the string 'self' instead of the model name, and you can refer to as-yet undefined models by using a string containing the model name. However, you can only use strings to refer to models in the same models.py file you cannot use a string to reference a model in a different application, or to reference a model that has been imported from elsewhere.

wzCByt <a href=”http://epvmwilwfiuu.com/“>epvmwilwfiuu</a>, [url=http://vgbixmpfskgj.com/]vgbixmpfskgj[/url], [link=http://ndylockyqkgc.com/]ndylockyqkgc[/link], http://govmwelxrfiq.com/

Its suggested, but not required, that the name of a ManyToManyField (toppings in the example) be a plural term describing the set of related model objects.

nrPcTI <a href=”http://gwdsikgpfkfx.com/“>gwdsikgpfkfx</a>, [url=http://fqcopieroseg.com/]fqcopieroseg[/url], [link=http://xrebnpxkafip.com/]xrebnpxkafip[/link], http://kpaprejfxufg.com/

Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship.

TJAnZY <a href=”http://xvacpzbfbkxi.com/“>xvacpzbfbkxi</a>, [url=http://lfoiapvqzrti.com/]lfoiapvqzrti[/url], [link=http://zgmqwkztagrt.com/]zgmqwkztagrt[/link], http://osktrrazjebz.com/

It doesnt matter which model gets the ManyToManyField , but you need it in only one of the models not in both.

1Bl7oT <a href=”http://epphitdetoos.com/“>epphitdetoos</a>, [url=http://hdebeujbyofp.com/]hdebeujbyofp[/url], [link=http://rjynxktskihv.com/]rjynxktskihv[/link], http://eluozbxntcqn.com/

If youre using the admin interface, ManyToManyField instances should go in the object thats going to be edited in the admin interface. In the preceding example, toppings is in Pizza (rather than Topping having a pizzas ManyToManyField ) because its more natural to think about a Pizza having toppings than a topping being on multiple pizzas. The way its set up in the example, the Pizza admin form would let users select the toppings.

3SkmGn <a href=”http://brxmsubwfndr.com/“>brxmsubwfndr</a>, [url=http://sxssxpmmfnyj.com/]sxssxpmmfnyj[/url], [link=http://zoqplwjomull.com/]zoqplwjomull[/link], http://vxxqzwsnmkbg.com/

ManyToManyField objects take a number of extra arguments for defining how the relationship should work (see Table B-6). All are optional.

JBFlaU <a href=”http://vsfpmxwdjegs.com/“>vsfpmxwdjegs</a>, [url=http://cyvjmleohtnu.com/]cyvjmleohtnu[/url], [link=http://rgfnqlmnmkgc.com/]rgfnqlmnmkgc[/link], http://onwrmzlknmnb.com/

Table B-6. ManyToManyField Options
Argument Description
related_name The name to use for the relation from the related object back to this one. See Appendix C for more information.
filter_interface Use a nifty, unobtrusive JavaScript filter interface instead of the usability-challenged <select multiple> in the admin form for this object. The value should be models.HORIZONTAL or models.VERTICAL (i.e., should the interface be stacked horizontally or vertically).
limit_choices_to See the description under ForeignKey .
symmetrical

Only used in the definition of ManyToManyField on self. Consider the following model:

class Person(models.Model):
    friends = models.ManyToManyField("self")

When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesnt add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical that is, if I am your friend, then you are my friend.

If you do not want symmetry in ManyToMany relationships with self , set symmetrical to False . This will force Django to add the descriptor for the reverse relationship, allowing ManyToMany relationships to be nonsymmetrical.

db_table The name of the table to create for storing the many-to-many data. If this is not provided, Django will assume a default name based upon the names of the two tables being joined.
琛˙-6. ManyToManyField閫夐」
鍙傛暟 鎻忚堪
related_name 鍏宠仈瀵硅薄鍙嶅悜寮曠敤鎻忚堪绗︺傛洿澶氫俊鎭弬瑙侀檮褰旵銆
filter_interface 鍦ㄨ繖涓璞$殑绠$悊鐣岄潰閲岄潰锛屼娇鐢ㄧ畝鍗曟槗鐢ㄧ殑JavaScript杩囨护鐣岄潰锛岃屼笉鏄娇鐢ㄥ彲鐢ㄦц緝宸殑 <select multiple> 銆傚畠鐨勫煎簲璇ユ槸 models.HORIZONTAL 鎴栬 models.VERTICAL 锛堝氨鏄鐣岄潰搴旇妯斁杩樻槸绔栨斁锛夈
limit_choices_to 鍙傝 ForeignKey 涓鏈」鐨勬弿杩般
symmetrical

浠呯敤浜庢ā鍨嬪畾涔夋寚鍚戣嚜韬殑 ManyToManyField 鐨勬儏鍐点傜湅涓嬮潰杩欎釜妯″瀷锛

class Person(models.Model):
    friends = models.ManyToManyField("self")

褰揇jango澶勭悊杩欎釜妯″瀷鏃讹紝浼氬彂鐜板畠鏈変竴涓寚鍚戣嚜韬殑 ManyToManyField 锛屽畠鍥犳灏变笉浼氬湪 Person 绫讳腑娣诲姞 person_set 灞炴с傝屽浜 ManyToManyField 锛屾垜浠細鍋囧畾杩欑 鍏崇郴鏄绉扮殑锛屽氨鏄锛屽鏋滄垜鏄綘鐨勬湅鍙嬶紝浣犱篃鏄垜鐨勬湅鍙嬨

鍦ㄥ selfManyToMany 鍏崇郴涓紝濡傛灉浣犱笉闇瑕佽繖绉嶅绉版э紝浣犲彲浠ユ妸 symmetrical 鐨勫艰涓 False 銆傝繖鏍峰氨浼氬己鍒禗jango缁欏叧绯荤殑鍙﹀涓鏂规坊鍔犳弿杩扮锛 浠庤屼娇杩欑鍏崇郴涓嶆槸瀵圭О鐨勩

db_table 鐢ㄦ潵淇濆瓨澶氬澶氭暟鎹殑琛ㄧ殑鍚嶅瓧銆傚鏋滄病鏈夋彁渚涙湰椤圭殑璇濓紝Django浼氭妸涓や釜琛ㄧ殑鍚嶅瓧杩炴帴璧锋潵褰 鍋氬瀵瑰鏁版嵁琛ㄧ殑榛樿鍚嶅瓧銆

Model Metadata Options

13gIw0 <a href=”http://sscmnzloyfgv.com/“>sscmnzloyfgv</a>, [url=http://spxlbmyezvpk.com/]spxlbmyezvpk[/url], [link=http://mmiqhlemjbwj.com/]mmiqhlemjbwj[/link], http://ggidkspvdbtt.com/

Model-specific metadata lives in a class Meta defined in the body of your model class:

q4wCqF <a href=”http://ujvctiyxerdr.com/“>ujvctiyxerdr</a>, [url=http://zfztncixykpp.com/]zfztncixykpp[/url], [link=http://tezeewkenxgk.com/]tezeewkenxgk[/link], http://bdbhykyxfxcz.com/

class Book(models.Model):
    title = models.CharField(maxlength=100)

    class Meta:
        # model metadata options go here
        ...

Model metadata is anything thats not a field, such as ordering options and so forth.

5X0yKB <a href=”http://xlfxtvanzsvs.com/“>xlfxtvanzsvs</a>, [url=http://vdidkvkivsny.com/]vdidkvkivsny[/url], [link=http://kstrtjdqpkte.com/]kstrtjdqpkte[/link], http://fnvjdqnmvggr.com/

The sections that follow present a list of all possible Meta options. No options are required. Adding class Meta to a model is completely optional.

wzu7mw <a href=”http://fdybefwcqpbm.com/“>fdybefwcqpbm</a>, [url=http://tbiwaaqsmmzv.com/]tbiwaaqsmmzv[/url], [link=http://nthrgpcwgtgx.com/]nthrgpcwgtgx[/link], http://suuwhzxvuexr.com/

db_table

db_table

The name of the database table to use for the model.

ptFBId <a href=”http://dizludlvdvam.com/“>dizludlvdvam</a>, [url=http://feigeddqkshf.com/]feigeddqkshf[/url], [link=http://pkmymjkwgrwj.com/]pkmymjkwgrwj[/link], http://hkcyuapirtpx.com/

To save you time, Django automatically derives the name of the database table from the name of your model class and the application that contains it. A models database table name is constructed by joining the models app label the name you used in manage.py startapp to the models class name, with an underscore between them.

6jcMFl <a href=”http://zwbfohqmihec.com/“>zwbfohqmihec</a>, [url=http://ugybhbfoaoom.com/]ugybhbfoaoom[/url], [link=http://isxnypoojtbq.com/]isxnypoojtbq[/link], http://lhtwtiwambvc.com/

For example, if you have an application books (as created by manage.py startapp books ), a model defined as class Book will have a database table named books .

1msLMM <a href=”http://xvmlagtfwijm.com/“>xvmlagtfwijm</a>, [url=http://lwycwnxymkxa.com/]lwycwnxymkxa[/url], [link=http://lnhwcjibczbr.com/]lnhwcjibczbr[/link], http://ujmkislozrxn.com/

To override the database table name, use the db_table parameter in class Meta :

閫氳繃澶嶅啓 class Meta 涓殑 db_table 鍙傛暟鍙互鏀瑰彉妯″瀷鏄犲皠鐨勬暟鎹簱琛ㄥ悕锛

class Book(models.Model):
    ...

    class Meta:
        db_table = 'things_to_read'

If this isnt given, Django will use app_label + '_' + model_class_name . See the section Table Names for more information.

QiUWjL <a href=”http://etehwczlfhby.com/“>etehwczlfhby</a>, [url=http://cvitpkdqztrq.com/]cvitpkdqztrq[/url], [link=http://grqclyedadhj.com/]grqclyedadhj[/link], http://bnmlrvdrphqv.com/

If your database table name is an SQL reserved word, or it contains characters that arent allowed in Python variable names (notably the hyphen), thats OK. Django quotes column and table names behind the scenes.

wlJKIi <a href=”http://kvejzmfwkvla.com/“>kvejzmfwkvla</a>, [url=http://kygvvswsmsvf.com/]kygvvswsmsvf[/url], [link=http://napevipgxgfj.com/]napevipgxgfj[/link], http://ckrltgibasoh.com/

get_latest_by

XZXXji <a href=”http://xidiruujzzbf.com/“>xidiruujzzbf</a>, [url=http://exmdfzejuiox.com/]exmdfzejuiox[/url], [link=http://fsopppjzbvqb.com/]fsopppjzbvqb[/link], http://grvpsajkzyml.com/

The name of a DateField or DateTimeField in the model. This specifies the default field to use in your model Manager s latest() method.

94R17m <a href=”http://efgunidzecqf.com/“>efgunidzecqf</a>, [url=http://bbonjfhkzdzi.com/]bbonjfhkzdzi[/url], [link=http://tiyeghfapzzd.com/]tiyeghfapzzd[/link], http://jahwpsnktnfu.com/

Heres an example:

YFcyGV <a href=”http://ffqwqyceztmc.com/“>ffqwqyceztmc</a>, [url=http://fsprcijzhury.com/]fsprcijzhury[/url], [link=http://dbyqvusgzten.com/]dbyqvusgzten[/link], http://ddcbhjbqhcqs.com/

class CustomerOrder(models.Model):
    order_date = models.DateTimeField()
    ...

    class Meta:
        get_latest_by = "order_date"

See Appendix C for more information on the latest() method.

鍏充簬 latest() 鏂规硶鐨勬洿澶氫俊鎭彲鍙傝冮檮褰旵銆

order_with_respect_to

YdjUFK <a href=”http://telxdshyupdv.com/“>telxdshyupdv</a>, [url=http://bpxxekmaggoo.com/]bpxxekmaggoo[/url], [link=http://rvqzecfwkwap.com/]rvqzecfwkwap[/link], http://bhzleleexump.com/

Marks this object as orderable with respect to the given field. This is almost always used with related objects to allow them to be ordered with respect to a parent object. For example, if an Answer relates to a Question object, and a question has more than one answer, and the order of answers matters, youd do this:

BDz71D <a href=”http://rliypzjqncmr.com/“>rliypzjqncmr</a>, [url=http://bffpzkzzjihq.com/]bffpzkzzjihq[/url], [link=http://pliqfdnbyonl.com/]pliqfdnbyonl[/link], http://eblhucuyyqnl.com/

class Answer(models.Model):
    question = models.ForeignKey(Question)
    # ...

    class Meta:
        order_with_respect_to = 'question'

ordering

mXiwpB <a href=”http://mjpckssfnxrr.com/“>mjpckssfnxrr</a>, [url=http://bvekvvnyuopy.com/]bvekvvnyuopy[/url], [link=http://piihretjzwfh.com/]piihretjzwfh[/link], http://ffomntjqeulv.com/

The default ordering for the object, for use when obtaining lists of objects:

z7cZ0i <a href=”http://dxwxvlwtzfeh.com/“>dxwxvlwtzfeh</a>, [url=http://szrgxumxqqxo.com/]szrgxumxqqxo[/url], [link=http://ojbwemtuntuw.com/]ojbwemtuntuw[/link], http://yyzjyuzxtlbh.com/

class Book(models.Model):
    title = models.CharField(maxlength=100)

    class Meta:
        ordering = ['title']

This is a tuple or list of strings. Each string is a field name with an optional - prefix, which indicates descending order. Fields without a leading - will be ordered ascending. Use the string "?" to order randomly.

3jTtLp <a href=”http://knckhvgxsxlb.com/“>knckhvgxsxlb</a>, [url=http://wrrfziuwnpze.com/]wrrfziuwnpze[/url], [link=http://ebelfvrsmzju.com/]ebelfvrsmzju[/link], http://xsgalxaywynp.com/

For example, to order by a title field in ascending order (i.e., A-Z), use this:

YmN84X <a href=”http://vilaoiqdzqaj.com/“>vilaoiqdzqaj</a>, [url=http://mblkjhogydyx.com/]mblkjhogydyx[/url], [link=http://nscaeuqdafqz.com/]nscaeuqdafqz[/link], http://zzlzclxbnbro.com/

ordering = ['title']

To order by title in descending order (i.e., Z-A), use this:

FjbSep <a href=”http://mtwjksqxborv.com/“>mtwjksqxborv</a>, [url=http://cbcqvaozxpix.com/]cbcqvaozxpix[/url], [link=http://ahqwhfexyggi.com/]ahqwhfexyggi[/link], http://djkfyjdvthws.com/

ordering = ['-title']

To order by title in descending order, and then by title in ascending order, use this:

EzKyzC <a href=”http://bpuhqrgyxlfu.com/“>bpuhqrgyxlfu</a>, [url=http://ioveitjshjpd.com/]ioveitjshjpd[/url], [link=http://facgutbfceyl.com/]facgutbfceyl[/link], http://agqrtbddgzkv.com/

ordering = ['-title', 'author']

Note that, regardless of how many fields are in ordering , the admin site uses only the first field.

娉ㄦ剰锛屾棤璁 ordering 涓湁澶氬皯瀛楁锛宎dmin鐣岄潰鍙娇鐢ㄧ涓涓瓧娈点

permissions

permissions

Extra permissions to enter into the permissions table when creating this object. Add, delete, and change permissions are automatically created for each object that has admin set. This example specifies an extra permission, can_deliver_pizzas :

DWUPFr <a href=”http://zjywwczpkqtk.com/“>zjywwczpkqtk</a>, [url=http://qjwywxmxkwqh.com/]qjwywxmxkwqh[/url], [link=http://iuydzmuwhzvd.com/]iuydzmuwhzvd[/link], http://hwwpxxexmyuo.com/

class Employee(models.Model):
    ...

    class Meta:
        permissions = (
            ("can_deliver_pizzas", "Can deliver pizzas"),
        )

This is a list or tuple of two tuples in the format (permission_code, human_readable_permission_name) .

h64M8C <a href=”http://xldflnwfvqut.com/“>xldflnwfvqut</a>, [url=http://niqpgqvgdtqy.com/]niqpgqvgdtqy[/url], [link=http://pamhftntfchr.com/]pamhftntfchr[/link], http://aeasfbmucchv.com/

See Chapter 12 for more on permissions.

鏈夊叧鏉冮檺鐨勬洿澶氫俊鎭弬瑙佺12绔犮

unique_together

a0Hrkd <a href=”http://iaqmkuwxxumb.com/“>iaqmkuwxxumb</a>, [url=http://ofegngpwsuhh.com/]ofegngpwsuhh[/url], [link=http://zitdmamqhbym.com/]zitdmamqhbym[/link], http://qsxshorrzwgm.com/

Sets of field names that, taken together, must be unique:

2MjoJT <a href=”http://uzlhhioqmbtg.com/“>uzlhhioqmbtg</a>, [url=http://zunpvwpjrkrj.com/]zunpvwpjrkrj[/url], [link=http://wxprpndxwkgy.com/]wxprpndxwkgy[/link], http://sgkjuprfrixh.com/

class Employee(models.Model):
    department = models.ForeignKey(Department)
    extension = models.CharField(maxlength=10)
    ...

    class Meta:
        unique_together = [("department", "extension")]

This is a list of lists of fields that must be unique when considered together. Its used in the Django admin interface and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).

杩欐槸涓涓敱涓浜涘瓧娈靛垪琛ㄧ粍鎴愮殑鍒楄〃锛屾瘡涓垪琛ㄩ噷鐨勫瓧娈电殑缁勫悎鍊煎繀椤绘槸鍞竴鐨勩傚畠鐢ㄤ簬Django绠$悊鐣岄潰锛岃屼笖鍦ㄦ暟鎹簱灞傛槸寮哄埗瑕佹眰鐨勶紙灏辨槸璇村湪 CREATE TABLE 璇彞涓細鍖呭惈涓浜 UNIQUE 璇彞锛夈

verbose_name

t77tUp <a href=”http://whojrdjihtrm.com/“>whojrdjihtrm</a>, [url=http://sinqinohypwo.com/]sinqinohypwo[/url], [link=http://blqbubcqbwds.com/]blqbubcqbwds[/link], http://ccyseljmmgbu.com/

A human-readable name for the object, singular:

4BSZAt <a href=”http://djaflphpxbjg.com/“>djaflphpxbjg</a>, [url=http://gxlddwzdpjvk.com/]gxlddwzdpjvk[/url], [link=http://jhnvrspkybsf.com/]jhnvrspkybsf[/link], http://yyicbgzatnrj.com/

class CustomerOrder(models.Model):
    order_date = models.DateTimeField()
    ...

    class Meta:
        verbose_name = "order"

If this isnt given, Django will use a adapted version of the class name in which CamelCase becomes camel case .

濡傛灉娌℃湁缁欏嚭姝ら夐」锛岄偅涔圖jango灏嗕細鏍规嵁绫诲悕鏉ュ緱鍒颁竴涓悕绉帮紝渚嬪 CamelCase 灏变細鍙樻垚 camel case

verbose_name_plural

UfWFBw <a href=”http://ilyxotrloovo.com/“>ilyxotrloovo</a>, [url=http://aogwttbwmxny.com/]aogwttbwmxny[/url], [link=http://dwfhccfhumql.com/]dwfhccfhumql[/link], http://opujnlbygptk.com/

The plural name for the object:

瀵硅薄澶嶆暟褰㈠紡鐨勫悕瀛楋細

class Sphynx(models.Model):
    ...

    class Meta:
        verbose_name_plural = "sphynges"

If this isnt given, Django will add an s to the verbose_name .

EGZW8N <a href=”http://byndqdkrbdkn.com/“>byndqdkrbdkn</a>, [url=http://msqfrvidrwzr.com/]msqfrvidrwzr[/url], [link=http://qbhtpepqmiap.com/]qbhtpepqmiap[/link], http://nhsqvmrjvnds.com/

Managers

60LJei <a href=”http://plhnnjddmlki.com/“>plhnnjddmlki</a>, [url=http://ltysrpbqxgeu.com/]ltysrpbqxgeu[/url], [link=http://vevgdraxrmwx.com/]vevgdraxrmwx[/link], http://xhkqrgklbupr.com/

A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application.

T9drol <a href=”http://eangvtfevkiy.com/“>eangvtfevkiy</a>, [url=http://wbvvcgnfnmrk.com/]wbvvcgnfnmrk[/url], [link=http://ciiixxyqwkwa.com/]ciiixxyqwkwa[/link], http://uhbbtqvxdqju.com/

The way Manager classes work is documented in Appendix C. This section specifically touches on model options that customize Manager behavior.

LuujQ6 <a href=”http://biwlfmrfzzas.com/“>biwlfmrfzzas</a>, [url=http://jrtwnkfewjwb.com/]jrtwnkfewjwb[/url], [link=http://rfhmumbemtsq.com/]rfhmumbemtsq[/link], http://wynbkcwyxxci.com/

Manager Names

绠$悊鍣ㄥ悕绉

By default, Django adds a Manager with the name objects to every Django model class. However, if you want to use objects as a field name, or if you want to use a name other than objects for the Manager , you can rename it on a per-model basis. To rename the Manager for a given class, define a class attribute of type models.Manager() on that model, for example:

A9sjj1 <a href=”http://qmyjwxwawhfk.com/“>qmyjwxwawhfk</a>, [url=http://giuyescfebfy.com/]giuyescfebfy[/url], [link=http://upfuebbdrnuh.com/]upfuebbdrnuh[/link], http://rlkiqiytkdqr.com/

from django.db import models

class Person(models.Model):
    ...

    people = models.Manager()

Using this example model, Person.objects will generate an AttributeError exception (since Person doesnt have a objects attribute), but Person.people.all() will provide a list of all Person objects.

w5LJjz <a href=”http://nmctodvzrypj.com/“>nmctodvzrypj</a>, [url=http://iuycwggtzahu.com/]iuycwggtzahu[/url], [link=http://uubizxqapwtf.com/]uubizxqapwtf[/link], http://lwkloizsvbvi.com/

Custom Managers

w4Rr3l <a href=”http://hxkvfclzprji.com/“>hxkvfclzprji</a>, [url=http://cgcmictbdtgc.com/]cgcmictbdtgc[/url], [link=http://kuzwmmchaldp.com/]kuzwmmchaldp[/link], http://ibyfqovdapgz.com/

You can use a custom Manager in a particular model by extending the base Manager class and instantiating your custom Manager in your model.

i2kzYA <a href=”http://tkfukseshcib.com/“>tkfukseshcib</a>, [url=http://pasqfavcpqra.com/]pasqfavcpqra[/url], [link=http://itzzkfieoikx.com/]itzzkfieoikx[/link], http://xnmbaowcdxtt.com/

There are two reasons you might want to customize a Manager : to add extra Manager methods, and/or to modify the initial QuerySet the Manager returns.

OTOTwd <a href=”http://dgwtcanxrozi.com/“>dgwtcanxrozi</a>, [url=http://izbmuqidjnxf.com/]izbmuqidjnxf[/url], [link=http://ydyfxtfwwvxm.com/]ydyfxtfwwvxm[/link], http://cycivjvljiza.com/

Adding Extra Manager Methods

2354Fc <a href=”http://qdtxytieiily.com/“>qdtxytieiily</a>, [url=http://kbbwwzyyjjlv.com/]kbbwwzyyjjlv[/url], [link=http://pqqulizfiimt.com/]pqqulizfiimt[/link], http://llzardlanyet.com/

Adding extra Manager methods is the preferred way to add table-level functionality to your models. (For row-level functionality that is, functions that act on a single instance of a model object use model methods (see below), not custom Manager methods.)

澧炲姞闄勫姞鐨 Manager 鏂规硶鏄湪妯″瀷涓鍔犳暟鎹〃绾у埆鐨勫姛鑳界殑棣栭夋柟娉曘傦紙瀵逛簬琛岀骇鍒殑鍔熻兘鈥斺斿氨鏄綔鐢ㄤ簬妯″瀷鐨勫崟涓疄渚嬩笂鐨勫姛鑳解斺旇浣跨敤妯″瀷鏂规硶锛堜笅闈㈡湁浠嬬粛锛夛紝鑰屼笉鏄畾鍒剁殑 Manager 鏂规硶銆傦級

A custom Manager method can return anything you want. It doesnt have to return a QuerySet .

wbyIGZ <a href=”http://bdvzelvswpyl.com/“>bdvzelvswpyl</a>, [url=http://tleuilchmsax.com/]tleuilchmsax[/url], [link=http://fhaaymygckju.com/]fhaaymygckju[/link], http://tyrjipbbjkrg.com/

For example, this custom Manager offers a method with_counts() , which returns a list of all OpinionPoll objects, each with an extra num_responses attribute that is the result of an aggregate query:

jpNASZ <a href=”http://wlfemapppidk.com/“>wlfemapppidk</a>, [url=http://hskgcqywvfhy.com/]hskgcqywvfhy[/url], [link=http://amumlqsppwdt.com/]amumlqsppwdt[/link], http://pyxrpwrvrpkx.com/

from django.db import connection

class PollManager(models.Manager):

    def with_counts(self):
        cursor = connection.cursor()
        cursor.execute("""
            SELECT p.id, p.question, p.poll_date, COUNT(*)
            FROM polls_opinionpoll p, polls_response r
            WHERE p.id = r.poll_id
            GROUP BY 1, 2, 3
            ORDER BY 3 DESC""")
        result_list = []
        for row in cursor.fetchall():
            p = self.model(id=row[0], question=row[1], poll_date=row[2])
            p.num_responses = row[3]
            result_list.append(p)
        return result_list

class OpinionPoll(models.Model):
    question = models.CharField(maxlength=200)
    poll_date = models.DateField()
    objects = PollManager()

class Response(models.Model):
    poll = models.ForeignKey(Poll)
    person_name = models.CharField(maxlength=50)
    response = models.TextField()

With this example, youd use OpinionPoll.objects.with_counts() to return that list of OpinionPoll objects with num_responses attributes.

鍦ㄨ繖涓緥瀛愪腑锛屼綘閫氳繃璋冪敤 OpinionPoll.objects.with_counts() 鏉ヨ繑鍥炵殑鎵鏈夌殑 OpinionPoll 瀵硅薄閮芥嫢鏈変竴涓 num_responses 灞炴с

Another thing to note about this example is that Manager methods can access self.model to get the model class to which theyre attached.

OU3cdE <a href=”http://pahnjwkqhexs.com/“>pahnjwkqhexs</a>, [url=http://faqniylltlsp.com/]faqniylltlsp[/url], [link=http://hcbgoujymltt.com/]hcbgoujymltt[/link], http://wkwwrrqlvwqz.com/

Modifying Initial Manager QuerySets

VCAtBU <a href=”http://auxobnzacaiw.com/“>auxobnzacaiw</a>, [url=http://wivgamqkyozz.com/]wivgamqkyozz[/url], [link=http://erzgotfabinf.com/]erzgotfabinf[/link], http://yekivblzjeie.com/

A Manager s base QuerySet returns all objects in the system. For example, using this model:

pSsPMh <a href=”http://xeajoerqlvrj.com/“>xeajoerqlvrj</a>, [url=http://wcmcnqjthvcm.com/]wcmcnqjthvcm[/url], [link=http://lklxnmndmwbb.com/]lklxnmndmwbb[/link], http://xegbtzthatng.com/

class Book(models.Model):
    title = models.CharField(maxlength=100)
    author = models.CharField(maxlength=50)

the statement Book.objects.all() will return all books in the database.

I7mkis <a href=”http://gerdptfgjyvk.com/“>gerdptfgjyvk</a>, [url=http://dixsmrzqccbz.com/]dixsmrzqccbz[/url], [link=http://ilyobnwdypgh.com/]ilyobnwdypgh[/link], http://onpbcrcphlzf.com/

You can override the base QuerySet by overriding the Manager.get_query_set() method. get_query_set() should return a QuerySet with the properties you require.

Vhvwk8 <a href=”http://nfotyzypsyqf.com/“>nfotyzypsyqf</a>, [url=http://mueslswboeiq.com/]mueslswboeiq[/url], [link=http://jezqwcgrybbm.com/]jezqwcgrybbm[/link], http://jwjvaabfwlyu.com/

For example, the following model has two managers one that returns all objects, and one that returns only the books by Roald Dahl:

3L5HuL <a href=”http://keecmfoprejw.com/“>keecmfoprejw</a>, [url=http://znmbrzypthjr.com/]znmbrzypthjr[/url], [link=http://mixsbersybfm.com/]mixsbersybfm[/link], http://vnzdlnonernu.com/

# First, define the Manager subclass.
class DahlBookManager(models.Manager):
    def get_query_set(self):
        return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')

# Then hook it into the Book model explicitly.
class Book(models.Model):
    title = models.CharField(maxlength=100)
    author = models.CharField(maxlength=50)

    objects = models.Manager() # The default manager.
    dahl_objects = DahlBookManager() # The Dahl-specific manager.

With this sample model, Book.objects.all() will return all books in the database, but Book.dahl_objects.all() will return only the ones written by Roald Dahl.

oiZLVc <a href=”http://uohufgieupph.com/“>uohufgieupph</a>, [url=http://lfkeiykfblgb.com/]lfkeiykfblgb[/url], [link=http://lwuvtueanfxs.com/]lwuvtueanfxs[/link], http://cxykuumzxmrl.com/

Of course, because get_query_set() returns a QuerySet object, you can use filter() , exclude() , and all the other QuerySet methods on it. So these statements are all legal:

GLjnJ8 <a href=”http://hmxmjdvwoxah.com/“>hmxmjdvwoxah</a>, [url=http://xnvdhaauucxe.com/]xnvdhaauucxe[/url], [link=http://mefdhebsdjfi.com/]mefdhebsdjfi[/link], http://vyqqjswvamvl.com/

Book.dahl_objects.all()
Book.dahl_objects.filter(title='Matilda')
Book.dahl_objects.count()

This example also points out another interesting technique: using multiple managers on the same model. You can attach as many Manager() instances to a model as youd like. This is an easy way to define common filters for your models. Heres an example:

IT4x1N <a href=”http://nutabyoiqwnp.com/“>nutabyoiqwnp</a>, [url=http://ktxzerbellle.com/]ktxzerbellle[/url], [link=http://jtqslfetyndx.com/]jtqslfetyndx[/link], http://vtwolegdqzul.com/

class MaleManager(models.Manager):
    def get_query_set(self):
        return super(MaleManager, self).get_query_set().filter(sex='M')

class FemaleManager(models.Manager):
    def get_query_set(self):
        return super(FemaleManager, self).get_query_set().filter(sex='F')

class Person(models.Model):
    first_name = models.CharField(maxlength=50)
    last_name = models.CharField(maxlength=50)
    sex = models.CharField(maxlength=1, choices=(('M', 'Male'), ('F', 'Female')))
    people = models.Manager()
    men = MaleManager()
    women = FemaleManager()

This example allows you to request Person.men.all() , Person.women.all() , and Person.people.all() , yielding predictable results.

sCncCk <a href=”http://qqyovvxekkai.com/“>qqyovvxekkai</a>, [url=http://akazdruhsfwr.com/]akazdruhsfwr[/url], [link=http://dwnabsynsvpu.com/]dwnabsynsvpu[/link], http://hbdjgxsskagj.com/

If you use custom Manager objects, take note that the first Manager Django encounters (in order by which theyre defined in the model) has a special status. Django interprets the first Manager defined in a class as the default Manager . Certain operations such as Djangos admin site use the default Manager to obtain lists of objects, so its generally a good idea for the first Manager to be relatively unfiltered. In the last example, the people Manager is defined first so its the default Manager .

FhlLFo <a href=”http://vsgwhqxhcckl.com/“>vsgwhqxhcckl</a>, [url=http://lsbttmznhtxy.com/]lsbttmznhtxy[/url], [link=http://ueimbzriverc.com/]ueimbzriverc[/link], http://ynqnfupqaphc.com/

Model Methods

No9tWK <a href=”http://eteeoasngotn.com/“>eteeoasngotn</a>, [url=http://nyihmksrhgpi.com/]nyihmksrhgpi[/url], [link=http://trmfcytmaewh.com/]trmfcytmaewh[/link], http://ifyqvqnopegb.com/

Define custom methods on a model to add custom row-level functionality to your objects. Whereas Manager methods are intended to do tablewide things, model methods should act on a particular model instance.

鑷畾涔塵odel鐨勬柟娉曞彲浠ヤ负浣犵殑model瀵硅薄鎻愪緵琛岀骇鐨勬搷浣滃姛鑳姐俉hereas Manager methods are intended to do tablewide things, model methods should act on a particular model instance.

This is a valuable technique for keeping business logic in one place: the model. For example, this model has a few custom methods:

LnpShb <a href=”http://yczyjlpgnfaf.com/“>yczyjlpgnfaf</a>, [url=http://ujjeohcmrozx.com/]ujjeohcmrozx[/url], [link=http://hylzoxfvwcge.com/]hylzoxfvwcge[/link], http://qfeiqmgazusg.com/

class Person(models.Model):
    first_name = models.CharField(maxlength=50)
    last_name = models.CharField(maxlength=50)
    birth_date = models.DateField()
    address = models.CharField(maxlength=100)
    city = models.CharField(maxlength=50)
    state = models.USStateField() # Yes, this is America-centric...

    def baby_boomer_status(self):
        """Returns the person's baby-boomer status."""
        import datetime
        if datetime.date(1945, 8, 1) <= self.birth_date <= datetime.date(1964, 12, 31):
            return "Baby boomer"
        if self.birth_date < datetime.date(1945, 8, 1):
            return "Pre-boomer"
        return "Post-boomer"

    def is_midwestern(self):
        """Returns True if this person is from the Midwest."""
        return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')

    @property
    def full_name(self):
        """Returns the person's full name."""
        return '%s %s' % (self.first_name, self.last_name)

The last method in this example is a property an attribute implemented by custom getter/setter user code. Properties are a nifty trick added to Python 2.2; you can read more about them at http://www.python.org/download/releases/2.2/descrintro/#property.

TbHgsN <a href=”http://kckrvumoknui.com/“>kckrvumoknui</a>, [url=http://hpqiyhqrykab.com/]hpqiyhqrykab[/url], [link=http://lrbqlrwlcuue.com/]lrbqlrwlcuue[/link], http://mzcwquklzlti.com/

There are also a handful of model methods that have special meaning to Python or Django. These methods are described in the sections that follow.

閭勬湁涓鍫嗘墜鍕曠殑妯″瀷鏂规硶锛屽皪Python or Django鏈夌壒鍒ョ殑鎰忕京銆 閫欎簺鏂规硶鍦ㄤ笅闈㈢殑娈佃惤瑁忔渻鎻忚堪銆

__str__

__str__

__str__() is a Python magic method that defines what should be returned if you call str() on the object. Django uses str(obj) (or the related function, unicode(obj) , described shortly) in a number of places, most notably as the value displayed to render an object in the Django admin site and as the value inserted into a template when it displays an object. Thus, you should always return a nice, human-readable string for the objects __str__ . Although this isnt required, its strongly encouraged.

__str__()鏄竴鍊婸ython 榄旇鐨勬柟娉曪紝瀹冨畾缇╀簡浠楹兼澅瑗垮皢浼氳杩斿洖鍋囧浣犺皟鐢ㄨ繖涓璞$殑str()銆侱jango 浣跨敤str(obj)(鎴栨槸鐩稿皪鎳夌殑鍑芥暩锛寀nicode(obj)锛岀啊鐭湴鎻忚堪)锛屽湪寰堝鍦版柟锛屾渶鏈夊悕锛屾槸閫欑鍑轰締鐨勫艰閫欏嬬墿浠堕噸绻湪Django 绠$悊绔欙紝鑰屼笖琚鍏ユǎ鏉跨殑鍊硷紝鐣跺畠灞曠ず涓鍊嬬墿浠躲傚洜姝わ紝浣犲繀闋堢附鏄繑鍥炰竴鍊嬪ソ鐨勶紝浜洪鍙畝鐨勫瓧涓诧紝灏嶉欏嬬墿浠禵_str__銆傚嵆浣块欎笉鏄繀闋堢殑锛屽畠閭勬槸寮峰垪鍦拌榧撳嫷 銆

Heres an example:

閫欒鏄竴鍊嬬瘎渚:

class Person(models.Model):
    first_name = models.CharField(maxlength=50)
    last_name = models.CharField(maxlength=50)

    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)

get_absolute_url

get_absolute_url

Define a get_absolute_url() method to tell Django how to calculate the URL for an object, for example:

鍙互閫氳繃瀹氫箟 get_absolute_url() 鏂规硶鏉ュ憡璇塂jango鎬庢牱寰楀埌涓涓璞$殑URL锛屼緥濡傦細

def get_absolute_url(self):
    return "/people/%i/" % self.id

Django uses this in its admin interface. If an object defines get_absolute_url() , the object-editing page will have a View on site link that will take you directly to the objects public view, according to get_absolute_url() .

Fv9jDH <a href=”http://uyninoehpvkx.com/“>uyninoehpvkx</a>, [url=http://vaibgebjztaj.com/]vaibgebjztaj[/url], [link=http://yxioptoumtwr.com/]yxioptoumtwr[/link], http://jfugkewnynrj.com/

Also, a couple of other bits of Django, such as the syndication-feed framework, use get_absolute_url() as a convenience to reward people whove defined the method.

1Zh52L <a href=”http://cfirbfaawvrq.com/“>cfirbfaawvrq</a>, [url=http://fwnbrwsjewzy.com/]fwnbrwsjewzy[/url], [link=http://fmvxgqgaagas.com/]fmvxgqgaagas[/link], http://kojplytbetzn.com/

Its good practice to use get_absolute_url() in templates, instead of hard-coding your objects URLs. For example, this template code is bad:

leHfag <a href=”http://epatxaltxvfh.com/“>epatxaltxvfh</a>, [url=http://tcaldmfaqruf.com/]tcaldmfaqruf[/url], [link=http://dryctqakfyjt.com/]dryctqakfyjt[/link], http://nyhzcazunzmo.com/

<a href="/people/{{ object.id }}/">{{ object.name }}</a>

But this template code is good:

浣嗚繖娈垫ā鏉夸唬鐮佸氨寰堜紭闆咃細

<a href="{{ object.get_absolute_url }}">{{ object.name }}</a>

The problem with the way we just wrote get_absolute_url() is that it slightly violates the DRY principle: the URL for this object is defined both in the URLconf file and in the model.

PvJ3wL <a href=”http://rygwiixtwfaz.com/“>rygwiixtwfaz</a>, [url=http://tghokilupxwk.com/]tghokilupxwk[/url], [link=http://vzixrufvghye.com/]vzixrufvghye[/link], http://jfjjereoktki.com/

You can further decouple your models from the URLconf using the permalink decorator. This decorator is passed the view function, a list of positional parameters, and (optionally) a dictionary of named parameters. Django then works out the correct full URL path using the URLconf, substituting the parameters you have given into the URL. For example, if your URLconf contained a line such as the following:

7sLbvE <a href=”http://mweevwmkknkv.com/“>mweevwmkknkv</a>, [url=http://smngveegkyfp.com/]smngveegkyfp[/url], [link=http://nsujmfplfqmd.com/]nsujmfplfqmd[/link], http://flabqxaktvei.com/

(r'^people/(\d+)/$', 'people.views.details'),

your model could have a get_absolute_url method that looked like this:

tFixRu <a href=”http://iiomckiovcak.com/“>iiomckiovcak</a>, [url=http://hoowsvppymfs.com/]hoowsvppymfs[/url], [link=http://wdywsumcziyj.com/]wdywsumcziyj[/link], http://mmtuwsaxelre.com/

@models.permalink
def get_absolute_url(self):
    return ('people.views.details', [str(self.id)])

Similarly, if you had a URLconf entry that looked like this:

涓庢绫讳技锛屽鏋滄湁杩欐牱鐨勪竴涓猆RLconf锛

(r'/archive/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$', archive_view)

you could reference this using permalink() as follows:

浣犲彲浠ュ儚涓嬮潰閭f牱鐢╬ermalink()鏉ュ紩鐢ㄨ繖涓摼鎺ワ細

@models.permalink
def get_absolute_url(self):
    return ('archive_view', (), {
        'year': self.created.year,
        'month': self.created.month,
        'day': self.created.day})

Notice that we specify an empty sequence for the second argument in this case, because we want to pass only keyword arguments, not named arguments.

娉ㄦ剰锛屾垜鍊戞寚鍑轰竴鍊嬬┖鐨勫簭鍒楋紝鍦ㄩ欑ó妗堜緥鐨勭浜屽嬪弮鏁革紝鍥犵偤鎴戝戞兂瑕佸偝鍏ュ彧鏈夐棞閸靛瓧鐨勫弮鏁革紝涓嶆槸宸插懡鍚嶇殑鍙冩暩銆

In this way, youre tying the models absolute URL to the view that is used to display it, without repeating the URL information anywhere. You can still use the get_absolute_url method in templates, as before.

鐢ㄩ欏嬫柟娉曪紝浣犲彲浠ヨ│钁楃敤妯″瀷鐨勭禃灏峌RL 锛屾寚鍚憊iew 锛岃鐢ㄤ締灞曠ず瀹冿紝 鑰屼笉瑕佸湪浠讳綍鍦版柟閲嶈URL 瑷婃伅銆備綘浠嶇劧鍙互浣跨敤get_absolute_url鏂规硶锛屽湪妯f澘瑁忥紝灏卞儚涔嬪墠涓妯

Executing Custom SQL

4wT82S <a href=”http://jfcnbgfnkugo.com/“>jfcnbgfnkugo</a>, [url=http://dtvisplwlkiv.com/]dtvisplwlkiv[/url], [link=http://aeitnsjpoytq.com/]aeitnsjpoytq[/link], http://qvuvfijqwtau.com/

Feel free to write custom SQL statements in custom model methods and module-level methods. The object django.db.connection represents the current database connection. To use it, call connection.cursor() to get a cursor object. Then, call cursor.execute(sql, [params]) to execute the SQL, and cursor.fetchone() or cursor.fetchall() to return the resulting rows:

IVnmJe <a href=”http://bvwdlvlpcmvs.com/“>bvwdlvlpcmvs</a>, [url=http://llaqrgizdoyg.com/]llaqrgizdoyg[/url], [link=http://jiqwupvxlxgf.com/]jiqwupvxlxgf[/link], http://nosleagbkkbi.com/

def my_custom_sql(self):
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
    row = cursor.fetchone()
    return row

connection and cursor mostly implement the standard Python DB-API (http://www.python.org/peps/pep-0249.html). If youre not familiar with the Python DB-API, note that the SQL statement in cursor.execute() uses placeholders, "%s" , rather than adding parameters directly within the SQL. If you use this technique, the underlying database library will automatically add quotes and escaping to your parameter(s) as necessary. (Also note that Django expects the "%s" placeholder, not the "?" placeholder, which is used by the SQLite Python bindings. This is for the sake of consistency and sanity.)

connection and cursor鏈甯歌瀵︿綔锛屽湪妯欐簴鐨 Python DB-API (http://www.python.org/peps/pep-0249.html).鍋囧浣犻倓涓嶅鐔熸倝Python DB-API锛屾敞鎰忓湪cursor.execute()SQL 鍙ュ瓙銆備娇鐢╬laceholders锛%s锛岀敋鏂肩洿鎺ュ湪SQL瑁忓姞鍙冩暩銆傚亣濡備綘浣跨敤閫欏嬫妧宸э紝搴曚笅鐨勮硣鏂欏韩鍑藉紡搴皣鑷嫊鐨勫姞涓婂紩铏熺郸浣犵殑鍙冩暩锛岃闇瑕佽屽畾銆(涔熸敞鎰廌jango 鏈熷緟%splaceholder鑰屼笉鏄?placeholder锛屽緦鑰呯敤鏂糞QLite Python閫f帴銆傞欐槸鐐轰簡绌╁畾鎬х殑鑰冮噺銆

A final note: If all you want to do is use a custom WHERE clause, you can just use the where , tables , and params arguments to the standard lookup API. See Appendix C.

bGD6sb <a href=”http://enmipsrebpkn.com/“>enmipsrebpkn</a>, [url=http://nlikjyohkfey.com/]nlikjyohkfey[/url], [link=http://jycloprmuhrq.com/]jycloprmuhrq[/link], http://rwrasyecvkhb.com/

Overriding Default Model Methods

lnSqzO <a href=”http://dyyybzjssdsb.com/“>dyyybzjssdsb</a>, [url=http://sxyzvssqxxin.com/]sxyzvssqxxin[/url], [link=http://ktkqwhavwhby.com/]ktkqwhavwhby[/link], http://swcixlqsdljc.com/

As explained in Appendix C, each model gets a few methods automatically most notably, save() and delete() . You can override these methods to alter behavior.

TYaSqR <a href=”http://ymeklkwwbatx.com/“>ymeklkwwbatx</a>, [url=http://wjcarpiatxjq.com/]wjcarpiatxjq[/url], [link=http://jedvuxxhmjyi.com/]jedvuxxhmjyi[/link], http://voeymuqfurxy.com/

A classic use-case for overriding the built-in methods is if you want something to happen whenever you save an object, for example:

bcMpwq <a href=”http://vqtcvfzdahdp.com/“>vqtcvfzdahdp</a>, [url=http://xjhuzvuagpkz.com/]xjhuzvuagpkz[/url], [link=http://mybpiupraqsq.com/]mybpiupraqsq[/link], http://vkjvyzzakyrr.com/

class Blog(models.Model):
    name = models.CharField(maxlength=100)
    tagline = models.TextField()

    def save(self):
        do_something()
        super(Blog, self).save() # Call the "real" save() method.
        do_something_else()

You can also prevent saving:

YrElQr <a href=”http://ynxdqlllzzio.com/“>ynxdqlllzzio</a>, [url=http://uixdabbxitqa.com/]uixdabbxitqa[/url], [link=http://jqqmxhjxbixf.com/]jqqmxhjxbixf[/link], http://veqqazomlbrh.com/

class Blog(models.Model):
    name = models.CharField(maxlength=100)
    tagline = models.TextField()

    def save(self):
        if self.name == "Yoko Ono's blog":
            return # Yoko shall never have her own blog!
        else:
            super(Blog, self).save() # Call the "real" save() method

Admin Options

Or94So <a href=”http://auqvqcnevuap.com/“>auqvqcnevuap</a>, [url=http://meafmxirjxxo.com/]meafmxirjxxo[/url], [link=http://qoevgyrylyag.com/]qoevgyrylyag[/link], http://jykabuuxbcvy.com/

The Admin class tells Django how to display the model in the admin site.

bUODc2 <a href=”http://icbryrmwparg.com/“>icbryrmwparg</a>, [url=http://ftwporjbssgj.com/]ftwporjbssgj[/url], [link=http://opnovnenxcub.com/]opnovnenxcub[/link], http://ptqrkulrtyve.com/

The following sections present a list of all possible Admin options. None of these options is required. To use an admin interface without specifying any options, use pass , like so:

J7dGXk <a href=”http://hwkgfnazccll.com/“>hwkgfnazccll</a>, [url=http://jpjzsaxvqjcz.com/]jpjzsaxvqjcz[/url], [link=http://sxggjjtajhdp.com/]sxggjjtajhdp[/link], http://xztbdpkeoepu.com/

class Admin:
    pass

Adding class Admin to a model is completely optional.

A6YyRH <a href=”http://iyzoszojratu.com/“>iyzoszojratu</a>, [url=http://iscvchsjmwsq.com/]iscvchsjmwsq[/url], [link=http://cthtqeoipqhz.com/]cthtqeoipqhz[/link], http://papcvcceilpv.com/

date_hierarchy

7SMCdB <a href=”http://hmomyyihrvsu.com/“>hmomyyihrvsu</a>, [url=http://gtflijbaejuj.com/]gtflijbaejuj[/url], [link=http://ehuaqtqvkeru.com/]ehuaqtqvkeru[/link], http://gbjwbghsfmsv.com/

Set date_hierarchy to the name of a DateField or DateTimeField in your model, and the change list page will include a date-based navigation using that field.

qaxoMK <a href=”http://mgrtbyrrjhfi.com/“>mgrtbyrrjhfi</a>, [url=http://ljztppbgjyhy.com/]ljztppbgjyhy[/url], [link=http://qbwhqvusanca.com/]qbwhqvusanca[/link], http://kkmytxlupffe.com/

Heres an example:

ZdKSTt <a href=”http://kbemtbgurbns.com/“>kbemtbgurbns</a>, [url=http://vuhqdhqzsael.com/]vuhqdhqzsael[/url], [link=http://zruvzeffkpob.com/]zruvzeffkpob[/link], http://rhmtxixuosxa.com/

class CustomerOrder(models.Model):
    order_date = models.DateTimeField()
    ...

    class Admin:
        date_hierarchy = "order_date"

fields

IVxg71 <a href=”http://eftpxxgnrekg.com/“>eftpxxgnrekg</a>, [url=http://nhsbyoibmhot.com/]nhsbyoibmhot[/url], [link=http://ftitphyknmmn.com/]ftitphyknmmn[/link], http://dijpfftdtzer.com/

Set fields to control the layout of admin interface add and change pages.

瑷畾fields渚嗘帶鍒剁鐞嗙暙闈㈢殑杓稿嚭锛屽姞涓婏紝淇敼闋侀潰

fields is a pretty complex nested data structure best demonstrated with an example. The following is taken from the FlatPage model thats part of django.contrib.flatpages :

娆勪綅锛屾槸涓鍊嬮潪甯歌闆滃发鐙鐨勮硣鏂欑祼妲 锛屽彲浠ュ緢濂界殑琚竴鍊嬬瘎渚嬪睍绀恒備互涓嬫槸鎿峰彇鑷狥latPage妯″瀷锛岄欐槸django.contrib.flatpages鐨勪竴閮ㄥ垎

class FlatPage(models.Model):
    ...

    class Admin:
        fields = (
            (None, {
                'fields': ('url', 'title', 'content', 'sites')
            }),
            ('Advanced options', {
                'classes': 'collapse',
                'fields' : ('enable_comments', 'registration_required', 'template_name')
            }),
        )

Formally, fields is a list of two tuples, in which each two-tuple represents a <fieldset> on the admin form page. (A <fieldset> is a section of the form.)

eejyMo <a href=”http://gceilydbxlue.com/“>gceilydbxlue</a>, [url=http://hrxzvjaofyfz.com/]hrxzvjaofyfz[/url], [link=http://efcytugbldzm.com/]efcytugbldzm[/link], http://pnsmxhalvgah.com/

The two-tuples are in the format (name, field_options) , where name is a string representing the title of the fieldset and field_options is a dictionary of information about the fieldset, including a list of fields to be displayed in it.

whDojh <a href=”http://lhkkqukjwkai.com/“>lhkkqukjwkai</a>, [url=http://gevoysqrsafj.com/]gevoysqrsafj[/url], [link=http://nnixugribacn.com/]nnixugribacn[/link], http://wwbgqwiowgcu.com/

If fields isnt given, Django will default to displaying each field that isnt an AutoField and has editable=True , in a single fieldset, in the same order as the fields are defined in the model.

1wuQp6 <a href=”http://sqrpcrfkectl.com/“>sqrpcrfkectl</a>, [url=http://zkrnsedefzzm.com/]zkrnsedefzzm[/url], [link=http://bcnmrtiruxnf.com/]bcnmrtiruxnf[/link], http://hpkloevpptha.com/

The field_options dictionary can have the keys described in the sections that follow.

JE1iBW <a href=”http://qcadxmlvoegc.com/“>qcadxmlvoegc</a>, [url=http://zvcrcytldnxk.com/]zvcrcytldnxk[/url], [link=http://dvysrtljteol.com/]dvysrtljteol[/link], http://mugunprltbnd.com/

fields
fields

A tuple of field names to display in this fieldset. This key is required.

eaGyAZ <a href=”http://xrprsouxnmno.com/“>xrprsouxnmno</a>, [url=http://xsmnsbokclxo.com/]xsmnsbokclxo[/url], [link=http://jjjnwaeucnhp.com/]jjjnwaeucnhp[/link], http://xxxwtjmhnmtw.com/

To display multiple fields on the same line, wrap those fields in their own tuple. In this example, the first_name and last_name fields will display on the same line:

F2G2pg <a href=”http://niapjgolcrhc.com/“>niapjgolcrhc</a>, [url=http://kywuwcxepyre.com/]kywuwcxepyre[/url], [link=http://sbnzuudzzrzi.com/]sbnzuudzzrzi[/link], http://tpfujwffndft.com/

'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),
classes

fbcGU1 <a href=”http://zcuctupvynum.com/“>zcuctupvynum</a>, [url=http://ekcwbjievazj.com/]ekcwbjievazj[/url], [link=http://deqpuogchyjz.com/]deqpuogchyjz[/link], http://rejzyuypqbxe.com/

A string containing extra CSS classes to apply to the fieldset.

涓涓寘鍚鍦╢ieldset涓婁娇鐢ㄧ殑CSS classes鐨勫瓧绗︿覆

Apply multiple classes by separating them with spaces:

閫氳繃绌烘牸鍒嗗紑宸蹭娇鐢ㄥ涓被锛

'classes': 'wide extrapretty',

Two useful classes defined by the default admin site stylesheet are collapse and wide . Fieldsets with the collapse style will be initially collapsed in the admin site and replaced with a small click to expand link. Fieldsets with the wide style will be given extra horizontal space.

kQvax1 <a href=”http://pfnbkptgnskx.com/“>pfnbkptgnskx</a>, [url=http://uticfblvzuxt.com/]uticfblvzuxt[/url], [link=http://jclrbpxuugsg.com/]jclrbpxuugsg[/link], http://saldqujlvyip.com/

description

idd25K <a href=”http://gftddddgojov.com/“>gftddddgojov</a>, [url=http://updaozymstdh.com/]updaozymstdh[/url], [link=http://xhfvkgbjcvrl.com/]xhfvkgbjcvrl[/link], http://yqofmeblxrcl.com/

A string of optional extra text to be displayed at the top of each fieldset, under the heading of the fieldset. Its used verbatim, so you can use any HTML and you must escape any special HTML characters (such as ampersands) yourself.

JTG4CH <a href=”http://hzqaacaktrgn.com/“>hzqaacaktrgn</a>, [url=http://utgasgjxbhfx.com/]utgasgjxbhfx[/url], [link=http://tlpadowtyluy.com/]tlpadowtyluy[/link], http://dfhuybuvlhbl.com/

js

PAeuqm <a href=”http://irmowhghfjgf.com/“>irmowhghfjgf</a>, [url=http://jlfrxidrtzic.com/]jlfrxidrtzic[/url], [link=http://daqtfuoqxqwt.com/]daqtfuoqxqwt[/link], http://dyxinywygrjr.com/

A list of strings representing URLs of JavaScript files to link into the admin screen via <script src=""> tags. This can be used to tweak a given type of admin page in JavaScript or to provide quick links to fill in default values for certain fields.

1mMNiN <a href=”http://naqykeusxljb.com/“>naqykeusxljb</a>, [url=http://yscklnygbybh.com/]yscklnygbybh[/url], [link=http://acbqegqbdtfn.com/]acbqegqbdtfn[/link], http://zxjljqdtqugt.com/

If you use relative URLs that is, URLs that dont start with http:// or / then the admin site will automatically prefix these links with settings.ADMIN_MEDIA_PREFIX .

list_display

list_display

Set list_display to control which fields are displayed on the change list page of the admin.

If you dont set list_display , the admin site will display a single column that displays the __str__() representation of each object.

Here are a few special cases to note about list_display :

杩欓噷鏄竴浜涗笓闂ㄥ叧浜巂`list_display``鐨勪緥瀛愶細

If the field is a ForeignKey , Django will display the __str__() of the related object.

g6GbVh <a href=”http://lzyzxejemzjw.com/“>lzyzxejemzjw</a>, [url=http://tsuthykruzkr.com/]tsuthykruzkr[/url], [link=http://xarkhwlagszw.com/]xarkhwlagszw[/link], http://tqmvpgpjpric.com/

ManyToManyField fields arent supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that methods name to list_display . (More information on custom methods in list_display shortly.)

dGlcgQ <a href=”http://iprqihmlxvod.com/“>iprqihmlxvod</a>, [url=http://kcvdagxjrkxa.com/]kcvdagxjrkxa[/url], [link=http://gsodubaogqud.com/]gsodubaogqud[/link], http://snaecnolpbxb.com/

If the field is a BooleanField or NullBooleanField , Django will display a pretty on or off icon instead of True or False .

E8kqGo <a href=”http://tjihiqymheuz.com/“>tjihiqymheuz</a>, [url=http://ctguiwscirkf.com/]ctguiwscirkf[/url], [link=http://ghauxgsjfuam.com/]ghauxgsjfuam[/link], http://tqjdcqlrshlx.com/

If the string given is a method of the model, Django will call it and display the output. This method should have a short_description function attribute, for use as the header for the field.

Heres a full example model:

86x3wr <a href=”http://kctcbldsfrdn.com/“>kctcbldsfrdn</a>, [url=http://gdukuqqsqppc.com/]gdukuqqsqppc[/url], [link=http://qdnxkecxkkec.com/]qdnxkecxkkec[/link], http://zuzpeekrjkhk.com/

class Person(models.Model):
    name = models.CharField(maxlength=50)
    birthday = models.DateField()

    class Admin:
        list_display = ('name', 'decade_born_in')

    def decade_born_in(self):
        return self.birthday.strftime('%Y')[:3] + "0's"
    decade_born_in.short_description = 'Birth decade'

If the string given is a method of the model, Django will HTML-escape the output by default. If youd rather not escape the output of the method, give the method an allow_tags attribute whose value is True .

gMVKpj <a href=”http://evitnbgmaosr.com/“>evitnbgmaosr</a>, [url=http://bqyhastwnilw.com/]bqyhastwnilw[/url], [link=http://sbobfuuthxnt.com/]sbobfuuthxnt[/link], http://ptanxrxpjprr.com/

Heres a full example model:

yphytq <a href=”http://gmvyrynyyahq.com/“>gmvyrynyyahq</a>, [url=http://txgswfndrwta.com/]txgswfndrwta[/url], [link=http://xdauvldellme.com/]xdauvldellme[/link], http://nvbauvgxzsbv.com/

class Person(models.Model):
    first_name = models.CharField(maxlength=50)
    last_name = models.CharField(maxlength=50)
    color_code = models.CharField(maxlength=6)

    class Admin:
        list_display = ('first_name', 'last_name', 'colored_name')

    def colored_name(self):
        return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
    colored_name.allow_tags = True

If the string given is a method of the model that returns True or False , Django will display a pretty on or off icon if you give the method a boolean attribute whose value is True .

Heres a full example model:

8apElY <a href=”http://yrufqnncwmtl.com/“>yrufqnncwmtl</a>, [url=http://bcgwcpzhnmpt.com/]bcgwcpzhnmpt[/url], [link=http://wpzmrhhiiztf.com/]wpzmrhhiiztf[/link], http://lqagkaphtsll.com/

class Person(models.Model):
    first_name = models.CharField(maxlength=50)
    birthday = models.DateField()

    class Admin:
        list_display = ('name', 'born_in_fifties')

    def born_in_fifties(self):
        return self.birthday.strftime('%Y')[:3] == 5
    born_in_fifties.boolean = True

The __str__() methods are just as valid in list_display as any other model method, so its perfectly OK to do this:

s1nIzH <a href=”http://tjdtsouiwiax.com/“>tjdtsouiwiax</a>, [url=http://uyudtmlsjglu.com/]uyudtmlsjglu[/url], [link=http://qgiychswhknz.com/]qgiychswhknz[/link], http://glgcjexwlvpy.com/

list_display = ('__str__', 'some_other_field')

Usually, elements of list_display that arent actual database fields cant be used in sorting (because Django does all the sorting at the database level).

However, if an element of list_display represents a certain database field, you can indicate this fact by setting the admin_order_field attribute of the item, for example:

3xBqNt <a href=”http://ndvondztohel.com/“>ndvondztohel</a>, [url=http://asclyqxdgiht.com/]asclyqxdgiht[/url], [link=http://xqnvhbmfksba.com/]xqnvhbmfksba[/link], http://phctuoxitimz.com/

class Person(models.Model):
    first_name = models.CharField(maxlength=50)
    color_code = models.CharField(maxlength=6)

    class Admin:
        list_display = ('first_name', 'colored_first_name')

    def colored_first_name(self):
        return '<span style="color: #%s;">%s</span>' % (self.color_code, self.first_name)
    colored_first_name.allow_tags = True
    colored_first_name.admin_order_field = 'first_name'

The preceding code will tell Django to order by the first_name field when trying to sort by colored_first_name in the admin site.

T2DLPa <a href=”http://jhnppcpcfmin.com/“>jhnppcpcfmin</a>, [url=http://hmhpkifkozei.com/]hmhpkifkozei[/url], [link=http://sulotsrblldm.com/]sulotsrblldm[/link], http://baexkghlghhd.com/

list_filter

FuOtHs <a href=”http://kphcpnemdlba.com/“>kphcpnemdlba</a>, [url=http://mlsgmbysptyn.com/]mlsgmbysptyn[/url], [link=http://avjrifxnkvgp.com/]avjrifxnkvgp[/link], http://fvwrqgwzpdpx.com/

Set list_filter to activate filters in the right sidebar of the change list page of the admin interface. This should be a list of field names, and each specified field should be either a BooleanField , DateField , DateTimeField , or ForeignKey .

ph8W7Q <a href=”http://kmqbncykkydd.com/“>kmqbncykkydd</a>, [url=http://wcahrijgdlat.com/]wcahrijgdlat[/url], [link=http://hobcwygwyqtc.com/]hobcwygwyqtc[/link], http://tkvvtjymjsds.com/

This example, taken from the django.contrib.auth.models.User model, shows how both list_display and list_filter work:

EJzGM0 <a href=”http://mhwmxembchmv.com/“>mhwmxembchmv</a>, [url=http://wesihcaufpom.com/]wesihcaufpom[/url], [link=http://zrglmivsrlcr.com/]zrglmivsrlcr[/link], http://qsiyponzuymn.com/

class User(models.Model):
    ...

    class Admin:
        list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
        list_filter = ('is_staff', 'is_superuser')

list_per_page

list_per_page

Set list_per_page to control how many items appear on each paginated admin change list page. By default, this is set to 100 .

2wNVQu <a href=”http://qwwbfzjzjvfu.com/“>qwwbfzjzjvfu</a>, [url=http://yimnopakydyj.com/]yimnopakydyj[/url], [link=http://mrwtcukmnhjq.com/]mrwtcukmnhjq[/link], http://pvhuisozolrk.com/

ordering

ordering

Set ordering to specify how objects on the admin change list page should be ordered. This should be a list or tuple in the same format as a models ordering parameter.

AUVpyP <a href=”http://awdohgubtjqj.com/“>awdohgubtjqj</a>, [url=http://ulesrtnnuydk.com/]ulesrtnnuydk[/url], [link=http://saecgtsewrsu.com/]saecgtsewrsu[/link], http://ffmirmhrnoru.com/

If this isnt provided, the Django admin interface will use the models default ordering.

save_as

XagYKW <a href=”http://pgsommmlsnlb.com/“>pgsommmlsnlb</a>, [url=http://xruzilflwbua.com/]xruzilflwbua[/url], [link=http://vcbexyazhdly.com/]vcbexyazhdly[/link], http://rwoeamwodzsv.com/

Set save_as to True to enable a save as feature on admin change forms.

phmoV3 <a href=”http://alsutlfgiozh.com/“>alsutlfgiozh</a>, [url=http://amrazhggydap.com/]amrazhggydap[/url], [link=http://kjbgkoktpses.com/]kjbgkoktpses[/link], http://zuoaccvwxska.com/

Normally, objects have three save options: Save, Save and continue editing, and Save and add another. If save_as is True , Save and add another will be replaced by a Save as button.

MAURrA <a href=”http://xogchuhaekfk.com/“>xogchuhaekfk</a>, [url=http://hmzzzysjsrvf.com/]hmzzzysjsrvf[/url], [link=http://omocicmixddt.com/]omocicmixddt[/link], http://jmagtlombhko.com/

Save as means the object will be saved as a new object (with a new ID), rather than the old object.

By default, save_as is set to False .

WP7Syx <a href=”http://hnicxgxlafum.com/“>hnicxgxlafum</a>, [url=http://vhooflupflxe.com/]vhooflupflxe[/url], [link=http://qswtkvkdplhk.com/]qswtkvkdplhk[/link], http://igqzlwonsucs.com/

save_on_top

O7Nl9x <a href=”http://vhugsrlueekr.com/“>vhugsrlueekr</a>, [url=http://ymxghtevvlkf.com/]ymxghtevvlkf[/url], [link=http://cbgqtttmidrp.com/]cbgqtttmidrp[/link], http://pvdgydrbfyer.com/

Set save_on_top to add save buttons across the top of your admin change forms.

璁剧疆 save_on_top 鍦ㄧ鐞嗗彉鏇磋〃鍗曠殑椤堕儴娣诲姞淇濆瓨鎸夐挳銆

Normally, the save buttons appear only at the bottom of the forms. If you set save_on_top , the buttons will appear both on the top and the bottom.

HLKzzd <a href=”http://vbcekgavadil.com/“>vbcekgavadil</a>, [url=http://uszvgeoiddwg.com/]uszvgeoiddwg[/url], [link=http://lqjzlwgnqtoo.com/]lqjzlwgnqtoo[/link], http://cuyzguferjtj.com/

By default, save_on_top is set to False .

8ONLUj <a href=”http://cizbmnmgpbuy.com/“>cizbmnmgpbuy</a>, [url=http://hvrjydqzceki.com/]hvrjydqzceki[/url], [link=http://sjpzlmnzlwvt.com/]sjpzlmnzlwvt[/link], http://kwtnaxfwdhft.com/

search_fields

T0xx3b <a href=”http://kfyxzdjhdyvx.com/“>kfyxzdjhdyvx</a>, [url=http://pxcrknxnwssb.com/]pxcrknxnwssb[/url], [link=http://xrblzygqerdm.com/]xrblzygqerdm[/link], http://aotiudiznyky.com/

Set search_fields to enable a search box on the admin change list page. This should be set to a list of field names that will be searched whenever somebody submits a search query in that text box.

CGU9eo <a href=”http://eijfjxoapbum.com/“>eijfjxoapbum</a>, [url=http://clnnwyfwhqvu.com/]clnnwyfwhqvu[/url], [link=http://ggqnqfarztlf.com/]ggqnqfarztlf[/link], http://puicrmosudub.com/

These fields should be some kind of text field, such as CharField or TextField . You can also perform a related lookup on a ForeignKey with the lookup API follow notation:

ZElkvM <a href=”http://evamizamxasj.com/“>evamizamxasj</a>, [url=http://nlpwcbotcxet.com/]nlpwcbotcxet[/url], [link=http://fhvtosewgtvl.com/]fhvtosewgtvl[/link], http://xfwqedcuogwa.com/

class Employee(models.Model):
    department = models.ForeignKey(Department)
    ...

    class Admin:
        search_fields = ['department__name']

When somebody does a search in the admin search box, Django splits the search query into words and returns all objects that contain each of the words, case insensitive, where each word must be in at least one of search_fields . For example, if search_fields is set to ['first_name', 'last_name'] and a user searches for john lennon , Django will do the equivalent of this SQL WHERE clause:

aj3Z94 <a href=”http://luixwhzaxcde.com/“>luixwhzaxcde</a>, [url=http://rauexnnpabpn.com/]rauexnnpabpn[/url], [link=http://phztrletzsvi.com/]phztrletzsvi[/link], http://rdfaxtdotiwd.com/

WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')

For faster and/or more restrictive searches, prefix the field name with an operator, as shown in Table B-7.

QePGaL <a href=”http://rbwjsuqycwsj.com/“>rbwjsuqycwsj</a>, [url=http://hxmiewyapclk.com/]hxmiewyapclk[/url], [link=http://gxzthdcuvbbz.com/]gxzthdcuvbbz[/link], http://aepqxdwjmhel.com/

Table B-7. Operators Allowed in search_fields
Operator Meaning
^

Matches the beginning of the field. For example, if search_fields is set to ['^first_name', '^last_name'] , and a user searches for john lennon , Django will do the equivalent of this SQL WHERE clause:

WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')

This query is more efficient than the normal '%john%' query, because the database only needs to check the beginning of a columns data, rather than seeking through the entire columns data. Plus, if the column has an index on it, some databases may be able to use the index for this query, even though its a LIKE query.

=

Matches exactly, case-insensitive. For example, if search_fields is set to ['=first_name', '=last_name'] and a user searches for john lennon , Django will do the equivalent of this SQL WHERE clause:

WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')

Note that the query input is split by spaces, so, following this example, its currently not possible to search for all records in which first_name is exactly 'john winston' (containing a space).

@ Performs a full-text match. This is like the default search method, but it uses an index. Currently this is available only for MySQL.
琛˙-7. search_fields涓厑璁镐娇鐢ㄧ殑鎿嶄綔绗
鎿嶄綔绗 鍚箟
^

鍖归厤瀛楁鐨勫紑澶淬備緥濡傦紝鎶 search_fields 璁剧疆鎴 ['^first_name', '^last_name'] 锛屽綋鐢ㄦ埛鎼滅储 john lennon 鏃讹紝Django鐩稿綋浜庢墽琛屼簡杩欐牱鐨凷QL WHERE 璇彞锛

WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')

杩欎釜鏌ヨ瑕佹瘮鎵ц鏅氱殑 '%john%' 鏌ヨ鏁堢巼楂橈紝鍥犱负鏁版嵁搴撳彧闇瑕佹鏌ユ瘡涓鍒楁暟鎹殑寮澶达紝鑰屼笉鐢ㄦ妸鏁 鍒楁暟鎹兘鎵竴閬嶃傛澶栵紝濡傛灉鏈夐拡瀵硅繖涓鍒楃殑绱㈠紩鐨勮瘽锛屾煇浜涙暟鎹簱鍙兘浼氬湪鏌ヨ涓娇鐢ㄧ储寮曪紝鍗充娇瀹冩槸涓涓 LIKE 鏌ヨ銆

=

绮剧‘鍖归厤锛屼笉鍖哄垎澶у皬鍐欍備緥濡傦紝鎶 search_fields 璁剧疆鎴 ['=first_name', '=last_name'] 锛屽綋 鐢ㄦ埛鎼滅储 john lennon 鏃讹紝Django鐩稿綋浜庢墽琛屼簡杩欐牱鐨凷QL WHERE 璇彞锛

WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')

璁颁綇锛屾悳绱㈣緭鍏ユ槸闈犵┖鏍兼潵鍒嗛殧鐨勶紝鎵浠ワ紝鍦ㄨ繖涓緥瀛愪腑杩樹笉鍙兘鎵惧嚭 first_name 鎭版伆鏄 'john winston' 锛堜腑闂存湁绌烘牸锛夌殑鎵鏈夎褰曘

@ 鎵ц鍏ㄦ枃鍖归厤銆傝繖涓拰榛樿鐨勬悳绱㈡柟娉曠被浼硷紝浣嗘槸瀹冧娇鐢ㄧ储寮曘傜洰鍓嶅彧鍦∕ySQL涓彲鐢ㄣ
Copyright 2006 Adrian Holovaty and Jacob Kaplan-Moss.
This work is licensed under the GNU Free Document License.
Hosting graciously provided by media temple
Chinese translate hosting by py3k.cn.