<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samandar Komilov on Medium]]></title>
        <description><![CDATA[Stories by Samandar Komilov on Medium]]></description>
        <link>https://medium.com/@samandar.komilov?source=rss-f359fabb2419------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7DVDsQN_gYFVT9xaeAVh9A.jpeg</url>
            <title>Stories by Samandar Komilov on Medium</title>
            <link>https://medium.com/@samandar.komilov?source=rss-f359fabb2419------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:54:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samandar.komilov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Process, Thread and Async: what the CPU actually runs?]]></title>
            <link>https://medium.com/@samandar.komilov/process-thread-and-async-what-the-cpu-actually-runs-7ddd0bd33044?source=rss-f359fabb2419------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ddd0bd33044</guid>
            <category><![CDATA[c-language]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Samandar Komilov]]></dc:creator>
            <pubDate>Sat, 11 Apr 2026 08:18:02 GMT</pubDate>
            <atom:updated>2026-04-11T11:39:46.197Z</atom:updated>
            <content:encoded><![CDATA[<p>Process haqida gap ketganida shu kabi ta’riflarga ko’zimiz tushgan bo’lsa kerak:</p><ul><li>Process is a <strong>running program</strong>;</li><li>Process is a <strong>smallest unit of abstraction</strong> that CPU runs;</li></ul><p>Va shu tufayli ehtimol aksarimiz (ehtimol faqat men) shunday tasavvurga kelib qolganmiz: <em>CPU schedule qiladi processlarni, aynan processlar CPU time oladi. </em>Bugun bu tasavvurimiz unchalik ham to’g’ri emasligini o’zimiz uchun isbotlaymiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*hU-ansRkLQzqF3mw.jpg" /></figure><h4>Process-only UNIX: The World Before Threads</h4><p>Unix 1969-yilda Bell Labs laboratoriyasida ishlab chiqildi. Ken Thompson tizimning dastlabki versiyasini minimalism asosida, elegant va eng asosiysi bitta markaziy abstraksiya ustiga qurgandi: <strong>Process</strong>. O’sha paytda process bu hamma narsa edi: dastur xotirasi uchun konteyner, CPU schedule qiladigan unit, isolation boundary ham (bir dastur boshqasi bilan aralashib ketmasligi). Birgina tushuncha butun tizimda barcha ishni qilardi, endi barcha tizimlarni shu arxitektura asosida qurish mumkin edi.</p><p>Dasturni yurg’izganingizda kernel unga process yaratgan (hozir ham). U process bir qism xotira, bir nechta ochiq fayllar, user identity (uni kim run qilgani) va CPU scheduler navbatidagi o’rnini o’zida saqlab turgan. CPU bo’shaganida, scheduler navbat bo’yicha processlarni tanlab ishga tushirgan. Agar process I/O sababli block bo’lib qolsa, kernel processni to’xtatib, stateni save qilib, boshqa processni run qilgan. Butun tizim bitta CPU va N ta processni rotatsiya qilishdan iborat edi.</p><p>Yangi process yaratish uchun UNIX fork() system callini bergan. Dasturimiz fork() ni chaqirganida (dasturimiz ishlab turibdi demak u process), kernel shu processni butunlay copy qilgan: xotirasi, ochiq fayllar, permissionlar; va unga yangi PID (process uchun yagona identifikator) bergan. C/C++ da yozib ko’rgan bo’lsak bilamiz,fork() dan qaytuvchi qiymat biz parent yoki child processda ekanimizni belgilaydi: agar biror &gt;0 raqam qaytsa, bu child PID, demak biz parent processdamiz; agar 0 qaytsa demak child processdamiz; oddiy if-else bilan amalga oshiriladi:</p><pre>#include &lt;fcntl.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;unistd.h&gt;<br><br>int main(void)<br>{<br>    pid_t pid;<br>    printf(&quot;Fork here.\n&quot;);<br>    pid = fork();<br><br>    if (pid == -1) {<br>        // If fork returns -1, there was an error!<br>        return (1);<br>    }<br>    printf(&quot;\nFork successful!\n&quot;);<br>    if (pid == 0) {<br>        // Fork&#39;s return value is 0: we are now in the child process<br>        printf(&quot;Child: I&#39;m the child, my internal pid is %d.\n&quot;, pid);<br>    }<br>    else if (pid &gt; 0) {<br>        // Fork&#39;s return value is not 0: which means we are in the parent process<br>        printf(&quot;Parent: I&#39;m the parent, my child&#39;s pid is %d.\n&quot;, pid);<br>    }<br>    return(0);<br>}</pre><p>Threads kirib kelishi nimani o’zgartirganini tushunish uchun Process aslida nimalarni o’z ichiga olishiga chuqurroq nazar tashlashimiz kerak.</p><h4>What a Process Actually Is</h4><p><strong>Virtual address space. </strong>Har bir process o’zini illyuziyasida yashaydi. Kernel, CPUning MMU (memory management unit) bilan ishlagan holda, har bir processga butun kompyuter RAMi seniki deydi: 64-bit tizimda bu 0 dan 2⁶⁴-1 gacha. Lekin “yolg’on” ham shu yerda: bu adreslarning hech biri haqiqiy RAM adresi emas, ular virtual. MMU orqa fonda virtual adreslarni haqiqiy adresga tarjima qilib turadi.</p><p><strong>File descriptor table. </strong>Har bir processda ochiq fayllar jadvali mavjud. Har safar open() system callini chaqirganimizda ochilayotgan faylni jadvalga kiritadi va jadvaldagi o’rni (integer), file descriptorni qaytaradi. Descriptor xuddi haqiqiy fayl va uning metadatasi (qaysiki kernel spaceda joylashgan)ga nisbatan pointer.</p><p><strong>Credentials.</strong> Har bir processda user ID, group ID kabi permission-related ma’lumotlar bo’ladi. Kernel ular orqali dasturni kim o’qiy/yoza/yurita oladi kim o’qiy/yoza/yurita olmaydi aniqlaydi.</p><p><strong>Va boshqalar.</strong> Process o’zi ishlab turgan direktoriyani, root direktoriyani, resurs limitlarini (RLIMIT_NOFILE, RLIMIT_AS, etc.) kabi ko’plab boshqa muhim ma’lumotlarni ham o’zida saqlaydi.</p><p>Shularning barchasini birlashtirib process deyishimiz mumkin, shunchaki “ishlab turgan dastur” emas. Dastur ishlashi CPU dastur ichidagi instructionlarni ishga tushirganida ro’y beradi. Processning o’zi esa virtual xotira, file descriptorlar, credentiallar va boshqa ko’plab ma’lumotlarni o’z ichiga oluvchi konteynerdir.</p><h4>The Problem That Couldn’t Be Ignored</h4><p>1980-yillarga kelib kompyuter tizimlari yanada shiddatli rivojlana bordi. Database serverlar yuzlab client connectionlarni, web serverlar bir vaqtda minglab HTTP requestlarni handle qilishiga to’g’ri kela boshladi. Xo’sh nima muammo, har biriga alohida fork() qilamiz! Bu rostdan ham ishlagan bo’lsa-da, qimmatga tusha boshladi. Lekin bundan ham kattaroq muammo — har bir fork() butun processni address space bilan birga copy qilgani uchun bu processlar o’zaro space share qilishi qiyin narsaga aylanib qoldi: pipelar, socketlar yoki shared memory, har birini o’z kamchiliklari bor edi. Har ikki process shunchaki bitta joyga ma’lumot yozib bir-birinikini o’qiy olishmasdi. Va bu aslida maqsadli edi — haqiqatan processni maqsadi isolation, lekin endi aynan shu narsa bilan kurashishi boshlangandi.</p><h4>The Invention of Threads</h4><p>1989-yilga kelib Andrew Birrell o’zining <em>“An Introduction to Programming with Threads” </em>maqolasida yangi g’oya bilan kirib keldi:</p><blockquote>Agar siz bir dastur ichida, bir joydagi ma’lumotlarni share qilgan holda, alohida processlar bilan boshingizni og’ritishni istamasangiz. Unda siz istagan narsa bir address space ichidagi bir nechta execution flowlaridir.</blockquote><p>Bu aynan thread tushunchasi edi. Birrell bu g’oyani osmondan olmadi, yoki birinchi bo’lib aytmadi: multiprogramming g’oyalari lightweight processes, tasks kabi nomlar ostida 70-yillardan buyon research qilib kelinayotgandi. Birrell qilgan ish esa thread tushunchasini omma uchun tushunarli va practical holatga olib keldi.</p><p><strong>Thread </strong>bu bir address spacedagi mustaqil execution oqimi bo’lib, o’z instruction pointer, stack va register statelariga ega. Ikki mustaqil process o’z mustaqil address spacelariga ega bo’lsa, ikki thread bir address spaceni share qiladi: ular bitta umumiy memory segmentni ko’radi. Ular bitta memory locationga ortiqcha IPC mexanizmlarisiz o’qiy va yoza oladi. Har bir thread o’zini stacki bo’ladi baribir, sababi har bir thread mustaqil ravishda funksiyalarni call qiladi, local variablelar e’lon qiladi va ular aralashib ketmasligi kerak. Har safar thread yaratilganida kernel default 8MB (linuxda) stack uchun ajratadi: bu butun boshli process address spaceni copy qilishdan ancha yengil operatsiya.</p><pre>#include &lt;pthread.h&gt;<br>#include &lt;stdio.h&gt;<br><br>void* foo(void* arg) {<br>    printf(&quot;Thread is running.\n&quot;);<br>    return NULL;<br>}<br><br>int main() {<br>    pthread_t thread1;<br>    pthread_create(&amp;thread1, NULL, foo, NULL);<br><br>    // Wait for thread to finish<br>    pthread_join(thread1, NULL);<br><br>    return 0;<br>}</pre><p>Bu kashfiyot o’z navbatida ko’p muammolarga yechim berdi: endi har bir HTTP connection uchun bitta thread ajratishimiz mumkin bo’ldi. Address space shared — heap bitta, ochiq fayllar va credentiallar bitta; faqat stack farq qiladi. Bir threaddan boshqasiga switch qilish ham ancha oson. Natijada endi CPU schedule qiladigan unit bu process emas threadga aylandi. Lekin linux shu nuqtada juda qiziq ish amalga oshiradi.</p><h4>Linux Doesn’t Know What a Thread Is</h4><p>Linux tizimida, processlar ham threadlar ham bitta entity bilan represent qilinadi: task_struct . Unda alohida process va thread degan tushunchalar yo’q. CPU scheduler task_struct entitylarni schedule qiladi. Iya, unda process bilan threadni qanday ajratib oladi? Farq — har bir task_struct boshqa task_struct lar bilan qanday resurslarni share qilishida ko’rinadi. fork() ham pthread_create() ham oxir oqibat orqa fonda clone() system callini chaqiradi. Bu syscall o’z navbatida yangi task_struct hosil qiladi. Lekin masala clone() system callga qanday flaglar berilishiga bog’liq.</p><p>fork() chaqirilganda kernel shunchaki clone() ni hech qanday flaglarsiz chaqiradi. Hosil bo’lgan task_struct otasining butun address spaceni, file descriptor jadvalini va credentiallarini copy qiladi. Flag bermadik degani hech nimani share qilma degani va bu process hosil qil degan buyruqqa sinonim.</p><p>pthread_create() chaqirilganda esa kernel clone() syscallini CLONE_VM | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD va yana bir qancha flaglar bilan chaqiradi.</p><ul><li>CLONE_VM : address spaceni copy qilma, share qil;</li><li>CLONE_FILES : file descriptor jadvalini copy qilma, share qil;</li><li>CLONE_SIGHAND : signallarni copy qilma, share qil;</li><li>CLONE_THREAD : thread group ID ni share qil.</li></ul><p>Demak, qachonki biz “process bu CPU run qiladigan eng kichik unit” deb o’ylaganimizda biz bitta daraja abstraksiyaga adashgan bo’lamiz. CPU task_struct ni run qiladi. CPU scheduler task_struct ni schedule qiladi, ya’ni CPU scheduling entity bu thread.task_struct esa yoki process yoki thread, flaglar asosida ma’lum bo’ladi.</p><p>Ammo shu o’rinda critical savol paydo bo’ladi: CPU scheduler threadlarni schedule qilsa, lekin hozirgina task_struct process ham bo’lishi mumkin deding-ku! Bu perspektiv bilan qarasak Linux uchun process bu shunchaki <strong>thread group</strong>. Har bitta processda eng kamida bitta thread bo’ladi degan gap shundan: har bir process bu 1 ta threaddan iborat thread group bo’ladi (eng kamida). Demak biz process va thread keskin farq qiladi degan tushunchani unutishimiz kerak. Linux uchun:</p><blockquote>task_struct schedule qilinadigan unit. Scheduler shu tasklarni run qiladi. Tasklar esa threadlar bo’lib, process bir nechta threaddan iborat guruhdir.</blockquote><h4>Why Threads Were Not Enough</h4><p>Threadlar bir process ichida bir nechta ishni qilish muammosiga yechim berdi. U serverlar minglab clientlarni fork() ni bosh og’rig’isiz handle qilishga yo’l ochdi, u IPC siz shared data ustida parallel computation amalga oshirish imkonini berdi. Biroq 90-yillarning oxiriga kelib internet rivojlandi, yuklamalar kattalashdi va model endi o’z muammolarini ko’rsata boshladi.</p><p>1999-yilga kelib Dan Kegel o’zining <em>“The C10K Problem” </em>maqolasida 10 mingta simultaneous connectionni bitta server bilan handle qilish muammosi haqida yozdi. Mavjud thread-per-connection modelida, 10 mingta connection bu 10 mingta thread. Bu degani har bir thread 8 MB stack size yesa, jami 80 GB xotira degani edi. Xotiraga ham xo’p desak, 10 mingta task_struct obyektlari CPU scheduler navbatida turishi va scheduler shu 10 mingta ichidan birini tanlashi kerak bo’ldi. Bu esa sekundiga minglagan context switch har biri o’zining overheadi bilan, CPU ga og’irlik qilishi ma’lum bo’ldi.</p><p>Muammo threadni o’zi bilan bog’liq emasdi aslida, muammo har bitta connectionga albatta bitta thread kerak deb tasavvur qilishda edi. Bu taxmin esa thread blocking I/O call qilganida (socketdan o’qish e.g.) to’xtab kutishga majbur bo’lishi, boshqa hech nima qila olmasligi va yana bir concurrent connection uchun bizga boshqa yangi thread kerakligidan kelib chiqqan edi.</p><h4>Async I/O</h4><p>Keyinchalik, aynan shu kutib qolishlarni oldini olish va yanada effektiv ishlash uchun I/O multiplexing g’oyalari amalga oshirildi: bitta thread ichida event loop bir nechta connectionni handle qila boshladi. Bu juda effektiv yechim bo’lib, agar bir connectionda I/O bo’lib qolsa event loop keyingi tasklarga o’tib ketaveradi va qachonki u yana tayyor bo’lsa kerneldan signal keladi, event loop uni pick qiladi va task kelgan joyidan davom etadi.</p><p>Linux kernel buni amalga oshirish uchun mexanizmlar taklif qildi: select() va poll() . Bunda bitta thread kernelga “bu file descriptorlardan qaysidir biri o’qish yoki yozish uchun tayyor bo’lganda menga signal ber” deb ayta olardi. Thread shu tarzda tayyor bo’lgan connection handlerni run qiladi, ish yakunlangach yana waiting statega qaytadi: bitta thread ko’plab connectionlarni handle qiladi. Bir qarashda bu g’alati tuyulishi mumkin: baribir o’sha muammo bo’ladiku, connectionlar kutib qoladiku. Lekin bir narsani unutmasligimiz kerak: connection oladigan umumiy vaqtning katta qismi I/O waiting. Connection handler funksiyani chaqirish juda kichik vaqt oladi va N-1 ta connection waitingda turganida 1 tasini run qilib yuborish hech qancha vaqt olmaydi. Aksincha, thread baribir kutib o’tirishidan xavotir olishimiz kerak).</p><p>select() vapoll() rivojlanmadi, sababi ular barcha monitor qilinayotgan file descriptorlar to’plamini kernelga har callda pass qilishiga to’g’ri keldi. Kernel esa 10 minglab descriptorlarni linear scan qilishi effektiv yechim bo’lmadi.</p><p>Shu sabab, 2002-yilga kelib Linux 2.5.44 versiyasiga epoll() qo’shildi. Unda descriptorlar epoll instancega bir marta register qilinadi. Kernel har bir register qilingan descriptor uchun maxsus hashtable-sifat data struktura ushlaydi. Qachonki socketga data kelsa, kernel descriptorni O(1) vaqtda “tayyor” deb belgilab qo’yadi. Har bir epoll_wait() callimiz faqatgina tayyor descriptorlarni qaytaradi. Ya’ni, 10 mingta connection bo’lsa ham atigi 10 tasi tayyor bo’lsa, 10 ta connection olamiz. Epoll shu sabab ham scale bo’ldi: Node.js event loopi, Python asyncio, nginx ichki ishlash modeli, Go runtime scheduler — barchasi epoll ustiga qurildi. Keyinchalik, 2019-yilda Linux 5.1 versiyasiga io_uring qo’shildi, bu epoll() ning system-call overheadidan ham qutilish imkonini berdi.</p><p>Xulosa qiladigan bo’lsak, Process va Thread biz tasavvur qilganimiz kabi mutlaqo boshqa tushunchalar emas, aksincha aslida bitta struct bilan handle qilinadigan entitylar ekan. Introductory kitoblarda bu topicga chuqur kirilmasligi sababi o’quvchini birdan overload qilmaslik deb taxmin qilamiz. Nima bo’lganda ham, endi concurrency mavzusi ketganida nisbatan kengroq tushunchalarimiz bor va quyidagi manbalar asosida researchni davom ettirishimiz mumkin.</p><h4>References:</h4><ol><li>Ritchie, D. M., &amp; Thompson, K. (1974). The UNIX Time-Sharing System. <em>Communications of the ACM, 17</em>(7), 365–375. <a href="https://dl.acm.org/doi/10.1145/361011.361061">https://dl.acm.org/doi/10.1145/361011.361061</a></li><li>Lions, J. (1977). <em>Lions’ Commentary on UNIX 6th Edition</em>. Peer-to-Peer Communications (republished 1996).</li><li>Birrell, A. D. (1989). <em>An Introduction to Programming with Threads</em>. DEC SRC Research Report 35. <a href="https://birrell.org/andrew/papers/035-Threads.pdf">https://birrell.org/andrew/papers/035-Threads.pdf</a></li><li>IEEE. (1995). <em>IEEE Std 1003.1c-1995: POSIX Threads Extension (pthreads)</em>. Institute of Electrical and Electronics Engineers.</li><li>IEEE. (2017). <em>IEEE Std 1003.1–2017: The Open Group Base Specifications Issue 7</em> — §3.347 Process. <a href="https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_347">https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_347</a></li><li>Kegel, D. (1999). <em>The C10K Problem</em>. <a href="http://www.kegel.com/c10k.html">http://www.kegel.com/c10k.html</a></li><li>Axboe, J. (2019). <em>Efficient IO with io_uring</em>. <a href="https://kernel.dk/io_uring.pdf">https://kernel.dk/io_uring.pdf</a></li><li>Torvalds, L. et al. <em>Linux Kernel Source</em> — include/linux/sched.h (struct task_struct). <a href="https://github.com/torvalds/linux/blob/master/include/linux/sched.h">https://github.com/torvalds/linux/blob/master/include/linux/sched.h</a></li><li>Torvalds, L. et al. <em>Linux Kernel Source</em> — arch/x86/kernel/process_64.c (__switch_to()). <a href="https://github.com/torvalds/linux/blob/master/arch/x86/kernel/process_64.c">https://github.com/torvalds/linux/blob/master/arch/x86/kernel/process_64.c</a></li><li>Kerrisk, M. (Ed.). fork(2) — Linux Programmer&#39;s Manual. <a href="https://man7.org/linux/man-pages/man2/fork.2.html">https://man7.org/linux/man-pages/man2/fork.2.html</a></li><li>Kerrisk, M. (Ed.). clone(2) — Linux Programmer&#39;s Manual. <a href="https://man7.org/linux/man-pages/man2/clone.2.html">https://man7.org/linux/man-pages/man2/clone.2.html</a></li><li>Kerrisk, M. (Ed.). pthreads(7) — Linux Programmer&#39;s Manual. <a href="https://man7.org/linux/man-pages/man7/pthreads.7.html">https://man7.org/linux/man-pages/man7/pthreads.7.html</a></li><li>Kerrisk, M. (Ed.). epoll(7) — Linux Programmer&#39;s Manual. <a href="https://man7.org/linux/man-pages/man7/epoll.7.html">https://man7.org/linux/man-pages/man7/epoll.7.html</a></li><li>Kerrisk, M. (Ed.). io_uring(7) — Linux Programmer&#39;s Manual. <a href="https://man7.org/linux/man-pages/man7/io_uring.7.html">https://man7.org/linux/man-pages/man7/io_uring.7.html</a></li><li>Bach, M. J. (1986). <em>The Design of the UNIX Operating System</em>. Prentice Hall.</li><li>Stevens, W. R., &amp; Rago, S. A. (2013). <em>Advanced Programming in the UNIX Environment</em> (3rd ed.). Addison-Wesley.</li><li>Kerrisk, M. (2010). <em>The Linux Programming Interface</em>. No Starch Press.</li><li>Love, R. (2010). <em>Linux Kernel Development</em> (3rd ed.). Addison-Wesley.</li><li>Tanenbaum, A. S. (2015). <em>Modern Operating Systems</em> (4th ed.). Pearson.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ddd0bd33044" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Joinlar qanday ishlaydi? Postgresda EXPLAIN ANALYZE va Pythonda simulation]]></title>
            <link>https://medium.com/@samandar.komilov/sql-joinlar-qanday-ishlaydi-postgresda-explain-analyze-va-pythonda-simulation-428e059ddace?source=rss-f359fabb2419------2</link>
            <guid isPermaLink="false">https://medium.com/p/428e059ddace</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Samandar Komilov]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 09:34:16 GMT</pubDate>
            <atom:updated>2025-01-26T09:48:22.496Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL joinlar eng fundamental bilimlardan biri ekanini bilamiz. Lekin shu o’rinda bir savol tug’iladi: <strong>Ular o’zi qanday ishlaydi?</strong> Orqa fonda DB server nima qiladiki bir nechta independent table’lardan related datani fetch qilib olib keladi?</p><p>Bugun shu masalani eng common bo’lgan INNER JOIN misolida, PostgreSQLda ko’rib chiqamiz. Bizda misol tariqasida Post va Author table’lari mavjud bo’ladi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2umxyrw8R26-mwGeYZxYHg.jpeg" /><figcaption>SQL logo</figcaption></figure><h4>Intuitive implementation</h4><p>INNER JOIN deganda miyaga eng birinchi keladigan, va aslida rostdan ham to’g’ri bo’lgan implementation bu nested loop orqali lookup qilishdir. Masalan, aytaylik postlarning title, posted_time fieldlari bilan birga uni yozgan odam ismi va tug’ilgan sanasini olishimiz kerak:</p><pre># Django-like syntax<br># posts = [...]<br># authors = [...]<br><br>res = []<br><br>for post in posts:<br>    for author in authors:<br>        if post.author_id == author.id:<br>            res.append(f&quot;{post.title} | {post.posted_time} | {author.name} | {author.birthdate}&quot;)<br><br>print(res)<br><br>##########<br># Post 1 | 2025-01-01 11:37:01 | Author 1 | 1997-09-07<br># Post 2 | 2025-01-03 18:13:41 | Author 2 | 2000-09-08<br># Post 3 | 2024-02-01 07:31:56 | Author 3 | 1988-02-06<br># ...</pre><p>Tushunarli, demak har bir post qatoriga borib, shu qatorda mavjud avtorning idsini yana alohida avtorlar jadvalidan qidirib topamiz: <em>O(n * k)</em>. Shuni SQL da yozganimizda qanday bo’lardi:</p><pre>SELECT p.title, p.posted_time, a.name, a.birthdate<br>FROM post AS p<br>INNER JOIN<br>author AS a<br>ON<br>p.author_id = a.id;<br><br>-- ---------------<br>-- Post 1 | 2025-01-01 11:37:01 | Author 1 | 1997-09-07<br>-- Post 2| 2025-01-03 18:13:41 | Author 2| 2000-09-08<br>-- Post 3| 2024-02-01 07:31:56 | Author 3| 1988-02-06<br>-- ...</pre><p>Logik jihatdan juda o’xshash, rostdan ham shunday. Lekin shu o’rinda savol tug’iladi: jadvallarimiz juda katta bo’lsa-chi? 2.5 millionta post va 1.3 millionta author, har bir jadvalni bittalab ko’rib chiqishga qancha “vaqt” ketadi axir? Eng yomon holatda (2.5*10⁶ * 1.3*10⁶ = 3.25 * 10¹²)!</p><h4>PostgreSQL analyzer</h4><p>Mazkur savolning javobini topish uchun internetni search qilganingizda postgresda <strong>EXPLAIN</strong> va <strong>EXPLAIN ANALYZE</strong> querylari bor ekaniga duch kelasiz. Ularni ishlatsak nima bo’ladi? PostgreSQL biz yozgan query uchun natijani qanday tartibda fetch qilayotgani haqida report beradi: qaysi algorithm qancha vaqtda va qay tartibda ishlatilyapti! Aytaylik sizda quyidagi query bor (<a href="https://t.me/voidplog/906">Sakila_db</a> misolida):</p><pre>EXPLAIN ANALYZE<br>SELECT a.first_name, f.title, fa.actor_id<br>FROM film AS f<br>INNER JOIN<br>film_actor AS fa<br>ON<br>fa.film_id = f.film_id<br>INNER JOIN<br>actor AS a<br>ON<br>a.actor_id = fa.actor_id<br>WHERE a.first_name LIKE &#39;JOHN%&#39;;</pre><p>Uni psql shellda yoki pgAdmin4 da run qilsangiz, quyidagi kabi <strong>Query plan</strong> chiqarib beradi:</p><figure><img alt="PGAdmin4 da EXPLAIN ANALYZE querysi run bo’lgandagi report" src="https://cdn-images-1.medium.com/max/770/1*3nh1ehFXAbcDYJSLaYEh2w.png" /><figcaption>EXPLAIN ANALYZE report</figcaption></figure><p>Haha, postgres ham nested loop ishlatgan ekanku! At least, bizning shu queryimiz nested loop holatiga tushdi. Xo’sh, bu yerda nima bo’lyapti?</p><h4>PostgreSQL Query Plan</h4><p>SQL is non-procedural language, ya’ni biz faqatgina <strong>nima</strong> kerak ekanini aytamiz, <strong>qanday</strong> ekanini esa DB server o’zi hal qiladi. Aynan shu qanday degan qismi haqidagi report — Query Plan. Biz postgresga biz nima xohlayotganimizni aytamiz, u esa bu so’rovni qay tartibda eng efficient yo’l bilan olishni tahlil qiladi va shu yo’l bilan olib beradi.</p><p>Postgres bu query uchun <strong>nested loop join</strong> strategiyasini tanladi. Bu usul kichik datasetlar uchun mos keladi. U strategiyani 3 bosqichda amalga oshirmoqda:</p><ul><li>actor jadvali bo’ylab <strong>sequential scan</strong> va filter by “JOHN%” wildcard: dastlab, aktyorlar jadvalini to’liq scan qilib, ismi John bilan boshlanadigan recordlarni filter qilib olmoqda. Buning uchun 1 ta loop ketdi, 200 tadan 197 ta record removed, 3 ta matched recordlar olindi.</li><li>film_actor many2many jadvali bo’ylab <strong>index-only scan: </strong>bu yerda esa faqatgina mavjud primary key indexi bo’ylab (film_actor_pkey) scan qilindi va actor_id hamda film_id olindi;</li><li>film jadvali bo’ylab<strong> index scan: </strong>bu yerda ham film_pkey primary key indexi yordamida filmning title’ni olib keldi.</li></ul><p>Xom fikr bilan qaraganda tekkis for loop bilan ham shu ishni qilsa bo’ladi. Lekin postgres bu yerda index scan ishlatmoqda, tabiiyki index unga qo’shimcha tezlik beradi (Indexlar haqida keyinroq). Shuningdek dastlabki sequential scan ham bor yo’g’i 3 ta result qaytargani uchun ikkinchi loop ancha kam vaqtda complete bo’ldi.</p><p>Queryimizdan oxirgi qatordagi filterni olib tashlasak esa boshqa manzarani ko’ramiz:</p><pre>EXPLAIN ANALYZE<br>SELECT a.first_name, f.title, fa.actor_id<br>FROM film AS f<br>INNER JOIN<br>film_actor AS fa<br>ON<br>fa.film_id = f.film_id<br>INNER JOIN<br>actor AS a<br>ON<br>a.actor_id = fa.actor_id;<br>-- WHERE a.first_name LIKE &#39;JOHN%&#39;;</pre><figure><img alt="PostgreSQL Query Plan result" src="https://cdn-images-1.medium.com/max/614/1*i8UItF0tOwWKwwAR8ICeMA.png" /><figcaption>Query Plan 2</figcaption></figure><p>Endi dastlabki loopdan 3 ta result emas 200 ta result qaytadi va u 200 ta bo’yicha yana alohida lookup qilish ortiqcha overhead. Buni sezgan postgres o’z navbatida yaxshiroq strategiyani ishga soldi: <strong>Hash Join</strong>.</p><h4>Hash Join qanday ishlaydi?</h4><p>Nomi ham aytib turganidek, bu strategiya qo’shimcha kichik virtual jadvalcha ochib, join qilinayotgan table’lar ichidan kichikrog’ini hashlab chiqish va hashtable’ning O(1) lookupidan foydalanishdan iborat. Quyidagi Pythonda simulation qilamiz:</p><pre># Django-like syntax<br><br>#1: Hashtable tuzib olish<br>author_hash = {author.id: author for author in authors}<br><br>#2: Probe (Hashtable orqali author_id match qilish)<br>res = []<br>for post in posts:<br>    if post.author_id in author_hash:  # O(1) vaqtda lookup<br>        author = author_hash[post.author_id]<br>        res.append(f&quot;{post.title} | {post.posted_time} | {author.name} | {author.birthdate}&quot;)<br><br>print(res)</pre><p>Menimcha hayratlanarli hech nima yo’q. Bu yerda qo’shimcha hashtable qurish uchun space ishlatish evaziga execution overheadni kamaytiryapmiz: O(n+m).</p><p>Rasmdagi holatda biz 3 ta tableni join qilyapmiz, shu sabab postgres 2 marta hash join va bir marta sequential scan qilmoqda. Sequential scan nima uchun deyilsa, Python kodda ham ko’rish mumkin bo’lgan inline for loop — hashtable’ni build qilish uchun film yoki author jadvalidan biri bo’ylab yurib chiqish kerak. Shuningdek postgres report qilyaptiki, har bir hashtable uchun mos ravishda 60 kB va 17 kB qo’shimcha Heapdan joy ochmoqda, va bu ham o’ziga xos efficiency bermoqda.</p><h4>Merge Join</h4><p>PostgreSQL yana bir boshqa strategiyadan ham foydalanadi — qachonki har ikki join qilinayotgan jadval join bo’layotgan key bo’yicha sort qilingan bo’lsa (qilinmagan bo’lsa o’zi sort qilishi kerak). Chunki aynan shu holatda mazkur usul yuqori efficiency beradi. Quyida Pythonda simulyatsiya qilamiz:</p><pre># Django-like syntax<br><br>#1: Har ikki datasetni join keylar orqali sort qilamiz<br>posts = sorted(posts, key=lambda x: x.author_id)<br>authors = sorted(authors, key=lambda x: x.id)<br><br>#2: Two pointers approach orqali match qilamiz<br>res = []<br>i, j = 0, 0<br><br>while i &lt; len(posts) and j &lt; len(authors):<br>    if posts[i].author_id == authors[j].id:<br>        res.append(f&quot;{posts[i].title} | {posts[i].posted_time} | {authors[j].name} | {authors[j].birthdate}&quot;)<br>        i += 1<br>    elif posts[i].author_id &lt; authors[j].id:<br>        i += 1<br>    else:<br>        j += 1<br><br>print(res)</pre><p>Har ikki table o’z join keylari orqali sort qilingach, uyog’i oson bo’lib qoladi: har ikki table’ni “bir vaqtda” iterate qilgan holda matching idlarni topib, topilganlarni yig’ib boriladi. Agar tablelar join key orqali sort qilingan bo’lsa, u holda tezlik O(n+m). Agar sort qilinmagan bo’lsa, har ikki jadvalni sortlash uchun O(nlog(n))+O(mlog(m)), va keyin merge qilish uchun jami O(nlog(n)+mlog(m)) vaqt oladi.</p><p>🏁 Umuman olganda, PostgreSQL bu algorithmlarni aynan qanday implement qilishi, unda qanday ichki data strukturalardan foydalanishi hozircha qorong’u. Lekin biz Python yordamida jarayonni simulate qilishga va biroz yaxshiroq tasavvurga ega bo’lishga harakat qildik. E’tiboringiz uchun rahmat.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=428e059ddace" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magic Tuples in Odoo: easily manage records in One2many and Many2many relationships]]></title>
            <link>https://medium.com/@samandar.komilov/magic-tuples-in-odoo-easily-manage-records-in-one2many-and-many2many-relationships-f741dcb36e23?source=rss-f359fabb2419------2</link>
            <guid isPermaLink="false">https://medium.com/p/f741dcb36e23</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[odoo-development]]></category>
            <category><![CDATA[odoo]]></category>
            <dc:creator><![CDATA[Samandar Komilov]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 14:00:12 GMT</pubDate>
            <atom:updated>2024-08-31T14:00:12.506Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of Odoo development, managing relational fields like One2many and Many2many effectively can make or break your application&#39;s functionality. Odoo&#39;s ORM provides several powerful command tuples to help developers perform various operations — from creating new records to updating, deleting, and managing relationships between records. However, understanding when and how to use these command tuples can be a bit daunting, especially for newcomers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGdlT_j-ZSOmY2249ti33Q.png" /><figcaption>Odoo Development: Magic Tuples in Odoo ORM</figcaption></figure><p>In this article, we’ll dive into the different types of these “Magic Tuples” available in Odoo ORM, and explain their usage with practical examples. Here are all of the magic tuple types available:</p><ul><li>(0, 0, {values}) — CREATE a new record</li><li>(1, ID, {values}) — UPDATE a record</li><li>(2, ID, 0) — DELETE a record</li><li>(3, ID, 0) — UNLINK a record (wait, what?)</li><li>(4, ID, 0) — LINK a record (hmm..)</li><li>(5, 0, 0) —CLEAR all records</li><li>(6, 0, [IDs]) — SET new records</li></ul><h4>1. Create a New Record</h4><p>Imagine you want to create a new <strong>Book</strong> record and immediately assign it to multiple <strong>Authors</strong>.</p><pre>book_vals = {<br>    &#39;name&#39;: &#39;Learning Python&#39;,<br>    &#39;isbn&#39;: &#39;9781449355739&#39;,<br>    &#39;author_ids&#39;: [<br>        (0, 0, {&#39;name&#39;: &#39;Mark Lutz&#39;, &#39;email&#39;: &#39;mark@example.com&#39;}),<br>        (0, 0, {&#39;name&#39;: &#39;David Ascher&#39;, &#39;email&#39;: &#39;david@example.com&#39;}),<br>    ]<br>}<br>new_book = self.env[&#39;library.book&#39;].create(book_vals)</pre><p>This code will create a new book called <em>“Learning Python” </em>while simultaneously creating its authors: <em>“Mark Lutz”</em> and <em>“David Ascher&quot;,</em> and linking them to this book.</p><h4>2. Update an Existing Record</h4><p>Let’s say you need to update the email address of an existing author linked to a book. You know the ID of that author object, let’s say it is “Mark Lutz” and his ID is 4:</p><pre>book = self.env[&#39;library.book&#39;].browse(1)<br>book.write({<br>    &#39;author_ids&#39;: [(1, 4, {&#39;email&#39;: &#39;newmark@example.com&#39;})]<br>})</pre><p>This will update the author with ID 4 and change his email to <em>&quot;newmark@example.com&quot;</em> without affecting their existing relationship with the book.</p><h4>3. Delete a Record (and Remove Relationship)</h4><p>Suppose you want to remove an author from the library’s database entirely with its relations with other records. In this case, we are deleting the author <em>“David Ascher” </em>with ID of 5:</p><pre>book = self.env[&#39;library.book&#39;].browse(1)<br>book.write({<br>    &#39;author_ids&#39;: [(2, 5, 0)]<br>})</pre><h4>4. Unlink a Record (Remove Relationship Only)</h4><p>If you only want to unlink an author from a book but keep the author’s record in the database, you would use:</p><pre>book = self.env[&#39;library.book&#39;].browse(1)<br>book.write({<br>    &#39;author_ids&#39;: [(3, 6, 0)]<br>})</pre><p>Delete and Unlink operations are different actually, even if they seem the same at first sight. The former one completely removes the database record with the specified ID, while the latter one just removes the relationship (the ID of that record from the related IDs field in the database table, if we think deeper).</p><h4>5. Link a Record (Add Relationship)</h4><p>Imagine you have an existing author in the database and want to add them as an author of another book.</p><pre>book = self.env[&#39;library.book&#39;].browse(1)<br>book.write({<br>    &#39;author_ids&#39;: [(4, 7, 0)]<br>})</pre><p>This is a reverse of the Unlink operation, which just adds a new relation (or a new ID to an appropriate field which contains related records’ IDs).</p><h4>6. Remove all Records</h4><p>Suppose you want to clear all authors linked to a book (without deleting any author records).</p><pre>book = self.env[&#39;library.book&#39;].browse(1)<br>book.write({<br>    &#39;author_ids&#39;: [(5, 0, 0)]<br>})</pre><p>This is a bulk unlink operation, we can say so I think at least. Because here, we are unlinking all author records from the book record.</p><h4>7. Replace all Records</h4><p>If you want to set specific authors as the only ones linked to a book, replacing any existing links, you would use:</p><pre>book = self.env[&#39;library.book&#39;].browse(1)<br>book.write({<br>    &#39;author_ids&#39;: [(6, 0, [8, 9])]<br>})</pre><p>This is also a bulk operation which replaces all related objects at once. The old relations will perish, but those old records persist in the database still.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f741dcb36e23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Quick Way to Customize Authentication Backends, User Manager, User and Permissions in Django]]></title>
            <link>https://medium.com/django-unleashed/a-quick-way-to-customize-authentication-backends-user-manager-user-and-permissions-in-django-54f9359e31eb?source=rss-f359fabb2419------2</link>
            <guid isPermaLink="false">https://medium.com/p/54f9359e31eb</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Samandar Komilov]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 19:26:56 GMT</pubDate>
            <atom:updated>2024-04-09T19:26:56.429Z</atom:updated>
            <content:encoded><![CDATA[<h4>Changing the default username-based authentication of Django to an Email-based authentication</h4><h3>Introduction</h3><p>In the realm of web development, Django stands tall as a robust framework that simplifies the creation of powerful web applications. One of its core functionalities lies in its authentication system, which manages user authentication, permissions, and groups effortlessly. However, there are scenarios where the default setup might not perfectly align with your project’s requirements.</p><p>Fear not, for Django offers a flexible solution to tailor authentication mechanisms to suit your needs. By customizing authentication backends, user managers, user models, and permissions, you can wield unparalleled control over user authentication and access control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KEZsprrzUfffYtYe.jpg" /></figure><p>In this article, we’ll embark on a journey through Django’s customization capabilities, exploring the creation of a custom authentication backend, user manager, user model, and permissions. Through concise examples and step-by-step guidance, you’ll gain insights into crafting a bespoke authentication system tailored precisely to your project’s specifications.</p><h3>Building a project: Blog app</h3><ol><li><strong>Create a django project and an app:</strong></li></ol><pre>django-admin startproject blog_project .<br>python manage.py startapp users</pre><p><strong>2. Define a Custom User Manager in </strong><strong>users/models.py :</strong></p><pre>from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin, Group as BaseGroup<br>from django.db import models<br><br><br>class CustomUserManager(BaseUserManager):<br>    def create_user(self, email, password=None, **extra_fields):<br>        if not email:<br>            raise ValueError(&#39;The Email Field must be set&#39;)<br>        email = self.normalize_email(email)<br>        user = self.model(email=email, **extra_fields)<br>        user.set_password(password)<br>        user.save(using=self._db)<br>        return user<br><br>    def create_superuser(self, email, password=None, **extra_fields):<br>        extra_fields.setdefault(&#39;is_staff&#39;, True)<br>        extra_fields.setdefault(&#39;is_superuser&#39;, True)<br><br>        if extra_fields.get(&#39;is_staff&#39;) is not True:<br>            raise ValueError(&#39;Superuser must have is_staff=True.&#39;)<br>        if extra_fields.get(&#39;is_superuser&#39;) is not True:<br>            raise ValueError(&#39;Superuser must have is_superuser=True.&#39;)<br>        <br>        return self.create_user(email, password, **extra_fields)</pre><p>First of all, we should get the meaning behind User Managers in Django.</p><p>👉 <strong>User Managers</strong> are classes that handle the creation, retrieval, updating, and deletion of user objects. They act as intermediaries between your Django application and the database, providing a layer of abstraction for interacting with user data.</p><p>By default, Django provides a UserManager class that handles the creation and management of user objects for the built-in User model. However, you can create your own custom UserManager to add additional functionality or modify the default behavior.</p><p>User managers typically provide methods for tasks such as creating new users, retrieving users by various criteria (e.g., username, email), updating user information, and deleting users. They may also include methods for handling authentication-related tasks, such as verifying passwords or creating tokens for password reset functionality.</p><p>✅ In the above code, we are extending the functionality of Basic User Manager to that can work with emails instead of usernames:</p><ul><li>create_user() — creates a user by checking the email field against emptiness, normalizing it and setting a password. Returns a user object.</li><li>create_superuser() — creates a superuser by defining 2 vital extra fields as True — staff status and superuser status of the user. If any of these fields are False, then the user is not a superuser, hence this function raises an error. Otherwise, creates a superuser.</li></ul><p><strong>3. Create a Custom User Model in </strong><strong>users/models.py again:</strong></p><pre>class CustomUser(AbstractBaseUser, PermissionsMixin):<br>    email = models.EmailField(unique=True)<br>    first_name = models.CharField(max_length=255, blank=True)<br>    last_name = models.CharField(max_length=255, blank=True)<br>    about = models.TextField(blank=True)<br>    is_active = models.BooleanField(default=True)<br>    is_staff = models.BooleanField(default=False)<br>    is_superuser = models.BooleanField(default=False)<br>    <br>    objects = CustomUserManager()<br><br>    USERNAME_FIELD = &#39;email&#39;<br>    REQUIRED_FIELDS = []<br><br>    def __str__(self):<br>        return self.email<br>    <br>    def has_perm(self, perm, obj=None):<br>        return self.is_staff<br><br>    def has_module_perms(self, app_label):<br>        return self.is_staff</pre><p>✅ Here, we are not extending the existing User Model of Django, instead we are creating a new User Model from scratch:</p><ul><li>objects — defines which User Manager manages these User objects.</li><li>USERNAME_FIELD = ‘email’ — specifies the field used as the unique identifier for a user when logging in. In this case, it’s the email field.</li><li>REQUIRED_FIELDS = [] — specifies any additional required fields when creating a user.</li><li>has_perm() method determines if the user has a specific permission (perm) within the system. It returns True if the user is a staff member (is_staff is True), otherwise False.</li><li>has_module_perms() method determines if the user has permissions to view the app with the given app_label. It returns True if the user is a staff member (is_staff is True), otherwise False.</li></ul><p><strong>4. Create a Custom Group Model in </strong><strong>users/models.py (optional):</strong></p><pre>class CustomGroup(BaseGroup):<br>    class Meta:<br>        proxy = False<br><br>    def __str__(self):<br>        return self.name</pre><p>Creating a Custom Group Model is not mandatory actually. Because, unless you even want to add custom fields other than name and permissions to the model (very rare), there is no point to change the default model. But anyway, we decided to consider this case too:</p><ul><li>You can add new fields as you wish, but here we didn’t do that.</li><li>proxy = False — this line ensures that the table for a CustomGroup model will not be created, it stays being as proxy model.</li></ul><p><strong>5. Create a Custom Authentication Backend in </strong><strong>users/backends.py by overriding </strong><strong>ModelBackend:</strong></p><pre>from django.contrib.auth import get_user_model<br>from django.contrib.auth.backends import ModelBackend<br><br><br>class EmailBackend(ModelBackend):<br>    def authenticate(self, request, email=None, password=None, **kwargs):<br>        user_model = get_user_model()<br>        try:<br>            user = user_model.objects.get(email=email)<br>            if user.check_password(password):<br>                return user<br>        except user_model.DoesNotExist:<br>            return None</pre><p>❓ Well, what is an authentication backend actually?</p><p>👉 <strong>Authentication Backend</strong> is a Python class responsible for <em>authenticating users</em>. While Django comes with a default authentication backend that authenticates users against the database-backed user model, you might encounter scenarios where you need to customize the authentication process.</p><p>Authentication backends allow you to integrate alternative authentication methods or authenticate against different sources such as LDAP, OAuth, or external APIs. They provide a way to extend Django’s authentication system beyond the default behavior.</p><p>❗️ Again, the primary purpose of an authentication backend is to verify the identity of users attempting to log in to the Django application. This involves validating credentials provided by the user, such as username and password, against the chosen authentication source.</p><p>In the above code, we are overriding the default ModelBackend and changing the behaviour of authenticate() method:</p><ul><li>instead of username field, we are checking for email field.</li></ul><p><strong>6. Configure </strong><strong>settings.py file:</strong></p><pre># Customization<br><br>AUTH_USER_MODEL = &#39;users.CustomUser&#39;<br>AUTH_GROUP_MODEL = &#39;users.CustomGroup&#39;<br><br>AUTHENTICATION_BACKENDS = [<br>    &#39;users.auth_backends.EmailBackend&#39;,<br>    &#39;django.contrib.auth.backends.ModelBackend&#39;,<br>]</pre><p>After creating Custom User and Custom Group Models, we have to specify the AUTH_USER_MODEL and AUTH_GROUP_MODEL settings in settings.py. AUTHENTICATION_BACKENDS also have to be changed as shown.</p><p><strong>7. Create a new app called </strong><strong>blog and configure the basic models and views:</strong></p><pre># blog/models.py<br><br>from django.db import models<br>from django.contrib.auth.models import User  # Use custom user model<br><br>class Post(models.Model):<br>    title = models.CharField(max_length=255)<br>    content = models.TextField()<br>    author = models.ForeignKey(User, on_delete=models.CASCADE)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return self.title</pre><pre>from django.shortcuts import render, redirect<br>from django.contrib.auth import authenticate, login, logout<br>from .models import Post<br>from .forms import CreatePostForm<br><br>def post_list(request):<br>    posts = Post.objects.all().order_by(&#39;-created_at&#39;)<br>    return render(request, &#39;blog/post_list.html&#39;, {&#39;posts&#39;: posts})<br><br>def create_post(request):<br>    if request.method == &#39;POST&#39;:<br>        form = CreatePostForm(request.POST)<br>        if form.is_valid():<br>            form.save(commit=False).author = request.user  # Associate post with user<br>            form.save()<br>            return redirect(&#39;post_list&#39;)<br>    else:<br>        form = CreatePostForm()</pre><p>This is just a test, you can configure your project as you want. For this reason, we didn’t consider urls, templates and other staff thoroughly.</p><p><strong>8. Create custom permissions for users in </strong><strong>users/permissions.py:</strong></p><pre>from django.contrib.auth.models import Permission<br><br>class CanEditPost(Permission):<br>    name = &#39;Can edit any post&#39;<br>    codename = &#39;can_edit_post&#39;<br><br>class CanPublishPost(Permission):<br>    name = &#39;Can publish own post&#39;<br>    codename = &#39;can_publish_post&#39;</pre><p>❓ What are permissions and why we need them?</p><p>👉 <strong>Permissions </strong>are a crucial component of the authorization system, determining <em>what actions users can perform</em> within the application. They govern access to views, models, and other resources based on the roles and privileges assigned to individual users or groups.</p><p>You can see default permissions that a User can have while creating it in admin panel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*JschTprtaMUTbUY525zkUQ.png" /></figure><p><strong>9. Modify the Custom User Model to include the permissions we created just now:</strong></p><pre>class CustomUser(AbstractBaseUser):<br>    # ... (existing code)<br><br>    class Meta:<br>        permissions = [<br>            (&#39;can_edit_post&#39;, &#39;Can edit any post&#39;),<br>            (&#39;can_publish_post&#39;, &#39;Can publish own post&#39;),<br>        ]<br><br>    objects = UserManager()<br><br>    # ... (existing code)</pre><p>After creating custom permissions, we have to specify that permissions in our Custom User Model to make them work.</p><h3>Conclusion</h3><p>Well, actually this is not a complete project. Actually, my goal was not doing that as well, rather I wanted to show how to create a “blueprint” for working with customized authentication elements of Django. I hope that goal has been achieved and if so I’m really happy. Provide feedbacks if you encounter something wrong or misleading. Thanks for your attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54f9359e31eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/a-quick-way-to-customize-authentication-backends-user-manager-user-and-permissions-in-django-54f9359e31eb">A Quick Way to Customize Authentication Backends, User Manager, User and Permissions in Django</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django REST framework: Serialization: Deeper Look. Part 1]]></title>
            <link>https://medium.com/django-unleashed/django-rest-framework-serialization-deeper-look-part-1-cf40108f9deb?source=rss-f359fabb2419------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf40108f9deb</guid>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Samandar Komilov]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 08:31:08 GMT</pubDate>
            <atom:updated>2024-03-24T08:31:08.869Z</atom:updated>
            <content:encoded><![CDATA[<p>Django REST framework is a powerful and flexible toolkit for building Web APIs. In DRF world, serializers play a pivotal role in this process, acting as the bridge between your Django models and API clients. They handle the crucial tasks of serialization (converting model instances into a format like JSON) and deserialization (converting incoming data back into model instances for storage). But DRF serializers offer much more than just basic data conversion. This article delves deeper into the world of DRF serialization, exploring core concepts like fields and arguments that empower you to create robust and efficient APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*N5Iep1wJY1iXgMzpHxzE8w.png" /></figure><p>First of all, it is essential to know what are the Serialization and Deserialization under the hood.</p><h3>Serialization</h3><p>DRF provides serializers, which are classes that define how data is converted into a format suitable for API responses (often JSON, XML, or others). Serializers map model instances, querysets, or Python data structures to representations that can be easily transmitted over the network.</p><p>The following example clarifies the situation:</p><pre>from rest_framework import serializers<br>from .models import Book<br><br>class BookSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Book<br>        fields = (&#39;title&#39;, &#39;author&#39;, &#39;publication_date&#39;)<br><br># Book instance<br>book = Book.objects.get(pk=1)<br><br># Serialization to JSON<br>serializer = BookSerializer(book)<br>json_data = serializer.data<br><br>print(json_data)  <br># Output: {&#39;title&#39;: &#39;The Great Gatsby&#39;, &#39;author&#39;: &#39;F. Scott Fitzgerald&#39;, &#39;publication_date&#39;: &#39;1925-04-10&#39;}</pre><ul><li><strong>BookSerializer</strong> is a serializer class which defines exactly what fields of the corresponding Django Model should be serialized into JSON. Here, our model is Book.</li><li>We got a single instance of Book with id=1. This instance is a complex data type, namely QuerySet. You can read about QuerySet <a href="https://www.w3schools.com/django/django_queryset.php">here</a>.</li><li><strong>BookSerializer(Book)</strong> serializes the complex data type into JSON format. Using .data we can get the json data and print the result.</li></ul><h3>Deserialization</h3><p>Deserialization allows converting data received through API requests (often JSON) back into Python objects. The following example shows the idea:</p><pre># Sample JSON data from a request<br>request_data = {&#39;title&#39;: &#39;Pride and Prejudice&#39;, &#39;author&#39;: &#39;Jane Austen&#39;, &#39;publication_date&#39;: &#39;1813-01-28&#39;}<br><br># Deserialization using BookSerializer<br>serializer = BookSerializer(data=request_data)<br># Check if data is valid<br>if serializer.is_valid():<br>    serializer.save()  # Saves the data as a new Book instance<br>    print(&quot;Book created successfully!&quot;)<br>else:<br>    print(&quot;Error:&quot;, serializer.errors)</pre><ul><li>Let’s assume we sent request to some endpoint and got the requested data in JSON as shown.</li><li>The same class, BookSerializer, can be used to deserialize the JSON data using data= parameter.</li><li>But we don’t know whether the requested data is valid. For instance, some required fields are empty, some fields does not pass the validation tests, etc. For this reason, we have to call .is_valid() method to make sure that the deserialized data is 100% valid and we can save it to database.</li></ul><p>Well, I hope you got the basic idea behind Serialization and Deserialization of Django REST Framework. Now, as a part 1, let’s do a thorough research on each of Serialization Fields with practical examples for the ones which are the hardest to understand.</p><h3>Serialization Fields</h3><p>Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.</p><p>The section mostly contains practices, not the whole documentation. You can read the official docs at the same time for better performance:</p><p>🔗 <a href="https://www.django-rest-framework.org/api-guide/fields/">https://www.django-rest-framework.org/api-guide/fields/</a></p><h4>Core Arguments</h4><p>Serializer Fields can take these arguments:</p><p>👉read_only — Read-only fields are included in the API output, but should not be included in the input during create or update operations. Defaults to False.</p><p>👉write_only — Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. Defaults to False. The below example shows the idea clearly:</p><pre>from django.contrib.auth.models import User<br>from rest_framework import serializers<br><br>class UserSerializer(serializers.ModelSerializer):<br>    password = serializers.CharField(write_only=True)<br><br>    class Meta:<br>        model = User<br>        fields = (&#39;username&#39;, &#39;email&#39;, &#39;password&#39;)  # Only username and email are included in output<br><br>    def create(self, validated_data):<br>        user = User.objects.create_user(**validated_data)<br>        user.set_password(validated_data[&#39;password&#39;])  # Set password securely (not serialized)<br>        user.save()<br>        return user</pre><blockquote>This is useful for sensitive data like passwords, internal calculations, or temporary values that you don’t want to expose publicly.</blockquote><p>👉required - means this field have to be supplied. If not, error will be raised. Default is False.</p><p>👉default - If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. Default fields are not actually a part of serialized data (output). They are defined within the serializer to specify default values for corresponding model fields when creating new model instances using the serializer’s save() method. Here are the main usage scenarios:</p><p><strong>Pre-Populating Fields. </strong>Use a default field to provide a value for a model field that might not always be included in the request data.</p><pre>from rest_framework import serializers<br>from .models import User<br><br>class UserSerializer(serializers.ModelSerializer):<br>    is_active = serializers.BooleanField(default=True)<br><br>    class Meta:<br>        model = User<br>        fields = (&#39;username&#39;, &#39;email&#39;, &#39;is_active&#39;)<br><br># Request data (might not always include is_active)<br>request_data = {&#39;username&#39;: &#39;john&#39;, &#39;email&#39;: &#39;john@example.com&#39;}<br><br># Serialization and creation with default<br>serializer = UserSerializer(data=request_data)<br>if serializer.is_valid():<br>    user = serializer.save()<br>    print(user.is_active)  # Output: True (default value used)</pre><p><strong>Conditional Defaults.</strong> You can define logic within the default field to provide dynamic values based on other data in the request, for instance using lambdas:</p><pre>from rest_framework import serializers<br>from .models import Product<br><br>class ProductSerializer(serializers.ModelSerializer):<br>    is_featured = serializers.BooleanField(<br>      default=lambda serializer: serializer.validated_data.get(&#39;price&#39;, 0) &gt; 100<br>      )<br><br>    class Meta:<br>        model = Product<br>        fields = (&#39;name&#39;, &#39;price&#39;, &#39;is_featured&#39;)<br><br># Request data with variable price<br>request_data1 = {&#39;name&#39;: &#39;T-Shirt&#39;, &#39;price&#39;: 80}<br>request_data2 = {&#39;name&#39;: &#39;Laptop&#39;, &#39;price&#39;: 1200}<br><br># Serialization and creation with conditional default<br>serializer1 = ProductSerializer(data=request_data1)<br>if serializer1.is_valid():<br>    product1 = serializer1.save()<br>    print(product1.is_featured)  # Output: False (default of False)<br><br>serializer2 = ProductSerializer(data=request_data2)<br>if serializer2.is_valid():<br>    product2 = serializer2.save()<br>    print(product2.is_featured)  # Output: True (default condition met)</pre><p>Here, we are setting default value depending on price of the product. If price &gt; 100, then the default is used (True), otherwise not (False).</p><p>👉allow_null — Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. Defaults to False.</p><p>👉source — this argument is crucial for customizing how data is retrieved for serialization and how data is assigned during deserialization. It allows you to:</p><p><strong>Access Nested Data.</strong> Use source to map a serializer field to a different attribute or method on the model instance, especially for nested relationships:</p><pre>from rest_framework import serializers<br>from .models import Author, Book<br><br>class AuthorSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Author<br>        fields = (&#39;name&#39;,)<br><br>class BookSerializer(serializers.ModelSerializer):<br>    author = AuthorSerializer(source=&#39;author_set.first()&#39;)  # Get first author<br><br>    class Meta:<br>        model = Book<br>        fields = (&#39;title&#39;, &#39;author&#39;)<br><br># Book instance with multiple authors<br>book = Book.objects.get(pk=1)<br><br># Serialization with source for nested data<br>serializer = BookSerializer(book)<br>print(serializer.data)  # Output: {&#39;title&#39;: &#39;The Catcher in the Rye&#39;, &#39;author&#39;: {&#39;name&#39;: &#39;J. D. Salinger&#39;}}</pre><p>Explanation:</p><ul><li>BookSerializer has an author field with source=&#39;author_set.first()&#39;. This tells DRF to retrieve the first author from the author_set related manager (assuming a ManyToManyField) and use the data from that object for serialization.</li><li>The AuthorSerializer is nested within the source to specify how the author data should be serialized.</li></ul><p><strong>Use Custom Methods.</strong> Define a custom method on your model or serializer to perform specific logic for data retrieval:</p><pre>from rest_framework import serializers<br><br>class Product(models.Model):<br>    name = models.CharField(max_length=100)<br>    price = models.DecimalField(max_digits=10, decimal_places=2)<br><br>    def get_discount_price(self):<br>        return self.price * 0.9  # Example discount calculation<br><br>class ProductSerializer(serializers.ModelSerializer):<br>    discount_price = serializers.DecimalField(source=&#39;get_discount_price&#39;, read_only=True)<br><br>    class Meta:<br>        model = Product<br>        fields = (&#39;name&#39;, &#39;price&#39;, &#39;discount_price&#39;)<br><br># Product instance<br>product = Product.objects.get(pk=1)<br><br># Serialization with source for custom method<br>serializer = ProductSerializer(product)<br>print(serializer.data)  # Output: {&#39;name&#39;: &#39;T-Shirt&#39;, &#39;price&#39;: 10.00, &#39;discount_price&#39;: 9.00}</pre><p>Explanation:</p><ul><li>ProductSerializer has a discount_price field with source=&#39;get_discount_price&#39;. This tells DRF to call the get_discount_price method on the product instance to get the value.</li><li>The read_only=True attribute prevents the discount_price field from being included in request data during deserialization.</li></ul><p><strong>Modify Data During Deserialization.</strong> Use source to transform data during deserialization before assigning it to the model field.</p><pre>from rest_framework import serializers<br><br>class TagSerializer(serializers.ModelSerializer):<br>    name = serializers.CharField(source=&#39;validate_name_upper&#39;)  # Transform to uppercase<br><br>    def validate_name_upper(self, value):<br>        if value.lower() == &#39;admin&#39;:<br>            raise serializers.ValidationError(&quot;Tag name cannot be &#39;admin&#39;&quot;)<br>        return value.upper()<br><br>    class Meta:<br>        model = Tag<br>        fields = (&#39;name&#39;,)<br><br># Request data with lowercase tag name<br>request_data = {&#39;name&#39;: &#39;new_tag&#39;}<br><br># Deserialization with source and validation<br>serializer = TagSerializer(data=request_data)<br>if serializer.is_valid():<br>    serializer.save()<br>else:<br>    print(&quot;Error:&quot;, serializer.errors)</pre><p>Explanation:</p><ul><li>TagSerializer has a name field with source=&#39;name_upper&#39;. This tells DRF to use the name_upper field (defined below) for deserialization.</li><li>The validate_name_upper method is used for validation before assigning the value to the name field of the model.</li></ul><p>👉error_messages — A dictionary of error codes to error messages.</p><p>👉label - A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.</p><p>👉help_text - A text string that may be used as a description of the field in HTML form fields or other descriptive elements.</p><p>👉initial - A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as you may do with any regular Django Field:</p><pre>import datetime<br>from rest_framework import serializers<br>class ExampleSerializer(serializers.Serializer):<br>    day = serializers.DateField(initial=datetime.date.today)</pre><p>👉style — A dictionary of key-value pairs that can be used to control how renderers should render the field. Two examples here are input_type and base_template:</p><pre># Use &lt;input type=&quot;password&quot;&gt; for the input.<br>password = serializers.CharField(<br>    style={&#39;input_type&#39;: &#39;password&#39;}<br>)<br><br># Use a radio input instead of a select input.<br>color_channel = serializers.ChoiceField(<br>    choices=[&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;],<br>    style={&#39;base_template&#39;: &#39;radio.html&#39;}<br>)</pre><p>We skipped validators, as we will consider them in the next part.</p><h4>BooleanFields</h4><p>👉BooleanField — A boolean representation. For instance:</p><pre>is_published = serializers.BooleanField(default=False)</pre><h4>String Fields</h4><p>👉CharField - A text representation. Optionally validates the text to be shorter than max_length and longer than min_length.</p><p>👉EmailField - A text representation, validates the text to be a valid e-mail address.</p><p>👉RegexField - A text representation, that validates the given value matches against a certain regular expression.</p><p>👉SlugField - A RegexField that validates the input against the pattern [a-zA-Z0-9_-]+.</p><p>👉URLField - A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http://&lt;host&gt;/&lt;path&gt;.</p><p>Consider an example for the above 5 fields at once:</p><pre>class ProductSerializer(serializers.Serializer):<br>    name = serializers.CharField(max_length=100)  # Textual field with max length<br>    description = serializers.CharField(required=False)  # Optional text field<br>    email = serializers.EmailField()  # Field for email addresses<br>    category_slug = serializers.SlugField()  # Field for slugs (alphanumeric with hyphens)<br>    website_url = serializers.URLField()  # Field for valid URLs</pre><p>👉UUIDField - A field that ensures the input is a valid UUID string. The to_internal_value method will return a uuid.UUID instance. On output the field will return a string in the canonical hyphenated format, for example: de305d54–75b4–431b-adb2-eb6b9e546013.</p><p>👉FilePathField - A field whose choices are limited to the filenames in a certain directory on the filesystem.</p><p>👉IPAddressField - A field that ensures the input is a valid IPv4 or IPv6 string.</p><p>Consider an example for the above 3 fields at once:</p><pre>class UploadSerializer(serializers.Serializer):<br>    upload_id = serializers.UUIDField(read_only=True)  # Unique identifier (generated)<br>    file_path = serializers.FilePathField(path=&#39;/uploads/&#39;, allow_files=True)  # File path within uploads folder<br>    ip_address = serializers.IPAddressField(protocol=&#39;both&#39;)  # Allows IPv4 and IPv6</pre><h4>Numeric Fields</h4><p>👉IntegerField - An integer representation.</p><p>👉FloatField - A floating point representation.</p><p>👉DecimalField - A decimal representation, represented in Python by a Decimal instance.</p><p>Consider an example for the above 3 fields at once:</p><pre>class ProductPriceSerializer(serializers.Serializer):<br>    price = serializers.IntegerField(min_value=0)  # Non-negative integer price<br>    discount = serializers.FloatField(max_value=1.0)  # Discount between 0 and 1 (inclusive)<br>    sale_price = serializers.DecimalField(max_digits=5, decimal_places=2)  # Price with 2 decimal places</pre><h4>Date and Time Fields</h4><p>👉DateTimeField - A date and time representation.</p><p>👉DateField - A date representation.</p><p>👉TimeField - A time representation.</p><p>👉DurationField - A Duration representation. The validated_data for these fields will contain a datetime.timedelta instance. The representation is a string following this format &#39;[DD] [HH:[MM:]]ss[.uuuuuu]&#39;.</p><p>Consider an example for the above 4 fields at once:</p><pre>class EventSerializer(serializers.Serializer):<br>    start_datetime = serializers.DateTimeField()  # Full date and time<br>    event_date = serializers.DateField()  # Just date information<br>    duration = serializers.DurationField()  # Time duration (e.g., hours, minutes)<br>    end_time = serializers.TimeField(required=False)  # Optional time field</pre><h4>Choice selection Fields</h4><p>👉ChoiceField - A field that can accept a value out of a limited set of choices. Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=… argument.</p><p>👉MultipleChoiceField - A field that can accept a set of zero, one or many values, chosen from a limited set of choices.</p><p>Consider an example for the above 2 fields at once:</p><pre>class ProductCategorySerializer(serializers.Serializer):<br>    STATUS_CHOICES = (<br>        (&#39;available&#39;, &#39;Available&#39;),<br>        (&#39;out_of_stock&#39;, &#39;Out of Stock&#39;),<br>        (&#39;discontinued&#39;, &#39;Discontinued&#39;),<br>    )<br><br>    category_name = serializers.CharField(max_length=50)<br>    status = serializers.ChoiceField(choices=STATUS_CHOICES)<br>    # Tags can have multiple values from a defined set<br>    tags = serializers.MultipleChoiceField(choices=(<br>        (&#39;electronics&#39;, &#39;Electronics&#39;),<br>        (&#39;clothing&#39;, &#39;Clothing&#39;),<br>        (&#39;home_goods&#39;, &#39;Home Goods&#39;),<br>    ))</pre><h4>File Upload Fields</h4><p>👉FileField - A file representation. Performs Django&#39;s standard FileField validation.</p><p>👉ImageField - An image representation. Validates the uploaded file content as matching a known image format.</p><p>Consider an example for the above 2 fields at once:</p><pre>class UploadSerializer(serializers.Serializer):<br>    document = serializers.FileField(use_url=True)  # Any file type<br>    profile_picture = serializers.ImageField(max_length=100, allow_empty_file=True)  # Image specific<br><br>    def validate_document(self, value):<br>        if value.content_type not in [&#39;application/pdf&#39;, &#39;text/plain&#39;]:<br>            raise serializers.ValidationError(&#39;Only PDF and text files allowed for documents.&#39;)<br>        return value</pre><h4>Composite Fields</h4><p>👉ListField — A field class that validates a list of objects. For example, to validate a list of integers you might use something like the following:</p><pre>scores = serializers.ListField(<br>   child=serializers.IntegerField(min_value=0, max_value=100)<br>)</pre><p>👉DictField — A field class that validates a dictionary of objects. The keys in DictField are always assumed to be string values. For example, to create a field that validates a mapping of strings to strings, you would write something like this:</p><pre>document = DictField(child=CharField())</pre><p>or:</p><pre>class UserDataSerializer(serializers.Serializer):<br>    # List of strings<br>    skills = serializers.ListField(child=serializers.CharField())<br>    # Dictionary of key-value pairs<br>    profile_data = serializers.DictField(child=serializers.CharField())</pre><p>👉HStoreField - A preconfigured DictField that is compatible with Django&#39;s postgres HStoreField. It has an efficient storage of key-value pairs compared to storing separate columns for each key. Additionally, well-suited for scenarios where you have a dynamic set of keys with string values.</p><p>👉JSONField - A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.</p><h4>Miscellaneous Fields</h4><p>👉ReadOnlyField - A field class that simply returns the value of the field without modification. This field is used by default with ModelSerializer when including field names that relate to an attribute rather than a model field.</p><p>👉HiddenField - A field class that does not take a value based on user input, but instead takes its value from a default value or callable. For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:</p><pre>modified = serializers.HiddenField(default=timezone.now)</pre><p>👉ModelField - A generic field that can be tied to any arbitrary model field. It is used to create serializer fields for custom model fields, without having to create a new custom serializer field.</p><p>👉SerializerMethodField - This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.</p><p>Consider an example for the above 4 fields at once:</p><pre>from rest_framework import serializers<br><br>class BookSerializer(serializers.Serializer):<br>    title = serializers.CharField(max_length=255)<br>    author = serializers.CharField(max_length=100)<br>    publication_date = serializers.DateField(read_only=True)  # Read-only field<br>    slug = serializers.ReadOnlyField(source=&#39;get_absolute_url&#39;)  # Derived value<br>    category = serializers.ModelField(model=&#39;categories.Category&#39;)  # Field for a related model<br>    average_rating = serializers.SerializerMethodField()  # Calculated field<br><br>    def get_average_rating(self, obj):<br>        # Logic to calculate and return the average rating for this book<br>        # (might involve querying the database or other calculations)<br>        average_rating = obj.reviews.aggregate(avg_rating=Avg(&#39;rating&#39;))[&#39;avg_rating&#39;]<br>        return average_rating or 0.0  # Handle cases where no reviews exist<br><br>    class Meta:<br>        model = &#39;books.Book&#39;<br>        fields = &#39;__all__&#39;</pre><p><em>❗️ We skipped validators field for now, as we will consider them more practically in the upcoming part of the article.</em></p><p>🏁 In order to work with Serializers with confidence and broad understanding, it is crucial to try at least once and analyze each field and core arguments. That’s it for today, thanks for your attention!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf40108f9deb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/django-rest-framework-serialization-deeper-look-part-1-cf40108f9deb">Django REST framework: Serialization: Deeper Look. Part 1</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django QuerySet API reference: alternative SQL queries for each method]]></title>
            <link>https://medium.com/django-unleashed/django-queryset-api-reference-alternative-sql-queries-for-each-method-457a916f244c?source=rss-f359fabb2419------2</link>
            <guid isPermaLink="false">https://medium.com/p/457a916f244c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Samandar Komilov]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 20:32:15 GMT</pubDate>
            <atom:updated>2024-02-07T16:17:21.332Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we are going to consider as much methods of QuerySet API of Django as possible, in the context of lower-level, raw SQL queries. I believe that, this will hugely benefit to understand the concepts more deeply. Of course, if you have some knowledge on SQL :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Psmb-Kk1LcYeA3JmW8YxWQ.png" /><figcaption>QuerySet API reference cover</figcaption></figure><p>Prior to start, let me share the official documentation of QuerySet API:</p><p>🔗 <a href="https://docs.djangoproject.com/en/5.0/ref/models/querysets/#annotate">https://docs.djangoproject.com/en/5.0/ref/models/querysets</a></p><p>I assume that you already know what is a QuerySet and basic ORM features of Django. Since we are to work with SQL queries directly, it is essential to derive the corresponding query of each method somehow. First of all, let’s create a new Django project with some models:</p><pre>$ py -m venv .env<br>$ .env\Scripts\activate<br>$ pip install django<br><br>$ django-admin startproject core .<br>$ python manage.py startapp inventory</pre><pre># inventory/models.py<br>from django.db import models<br><br>class Car(models.Model):<br>    name = models.CharField(max_length=255)<br>    factory = models.CharField(max_length=255)<br>    year = models.SmallIntegerField()<br><br>    def __str__(self):<br>        return self.name</pre><pre>$ python manage.py makemigrations<br>$ python manage.py migrate</pre><p>️️⚠️ I will use Django Shell to test the functionality. Make sure that you have run your project before accessing the Shell:</p><pre>$ python manage.py runserver</pre><p>Then, on another Terminal:</p><pre>$ python manage.py shell</pre><p>Keep in mind that Django Shell runs from project root folder. So, in order to access the models we have previously created:</p><pre>&gt;&gt;&gt; from inventory.models import Car</pre><p>Now, we can use Shell to test the QuerySet methods effectively. Let’s first consider .all() method as it is the easiest one so far:</p><pre>&gt;&gt;&gt; print(Car.objects.all().query)<br>SELECT &quot;inventory_car&quot;.&quot;id&quot;, &quot;inventory_car&quot;.&quot;name&quot;, &quot;inventory_car&quot;.&quot;factory&quot;, &quot;inventory_car&quot;.&quot;year&quot; FROM &quot;inventory_car&quot;</pre><p>✅ Using this approach, we can determine the underlying SQL queries for each method.</p><p>Basically, QuerySet API methods are classified into 5 categories:</p><ul><li><em>Methods that return new QuerySets;</em></li><li><em>Operators that return new QuerySets;</em></li><li><em>Methods that do not return new QuerySets;</em></li><li><em>Field lookups;</em></li><li><em>Aggregate functions.</em></li></ul><p>It may be difficult to show every method, but I try as much as I can. From now on, I only show the method name, its short description and usage followed by corresponding alternative SQL query, since all other information is available in the official documentation.</p><p>👉 all() — Returns a copy of the current QuerySet.</p><pre>&gt;&gt;&gt; Car.objects.all()</pre><pre>SELECT * FROM inventory_car;</pre><p>👉 filter() — Returns a new QuerySet containing objects that <em>match</em> the given lookup parameters.</p><pre>&gt;&gt;&gt; Car.objects.filter(factory=&quot;BYD&quot;)</pre><pre>SELECT * FROM inventory_car WHERE inventory_car.factory = BYD;</pre><p>👉 exclude() — Returns a new QuerySet containing objects that <em>do not match</em> the given lookup parameters.</p><pre>&gt;&gt;&gt; Car.objects.exclude(year=2013)<br><br># Other usages<br>&gt;&gt;&gt; Car.objects.exclude(year=2020, factory=&quot;BYD&quot;)<br>&gt;&gt;&gt; Car.objects.exclude(year=2020).exclude(factory=&quot;BYD&quot;)</pre><pre>SELECT * FROM inventory_car WHERE NOT (inventory_car.year = 2013)</pre><p>👉 annotate() — allows to add calculated fields to each object in the queryset based on some aggregation or annotation performed on related fields (similar to GROUP BY)</p><pre>&gt;&gt;&gt; Car.objects.annotate(total_cars=Count(&#39;factory&#39;))</pre><pre>SELECT &quot;inventory_car&quot;.&quot;id&quot;, &quot;inventory_car&quot;.&quot;name&quot;, &quot;inventory_car&quot;.&quot;factory&quot;, &quot;inventory_car&quot;.&quot;year&quot;, COUNT(&quot;inventory_car&quot;.&quot;factory&quot;) AS &quot;total_cars&quot; <br>FROM &quot;inventory_car&quot; GROUP BY &quot;inventory_car&quot;.&quot;id&quot;, &quot;inventory_car&quot;.&quot;name&quot;, &quot;inventory_car&quot;.&quot;factory&quot;, &quot;inventory_car&quot;.&quot;year&quot;</pre><p>👉 order_by() — allows to define the order in which database rows should be retrieved based on one or more fields.</p><pre>&gt;&gt;&gt; Car.objects.all().order_by(&#39;name&#39;)<br><br># Plus, we can give the direction:<br>&gt;&gt;&gt; Car.objects.all().order_by(&#39;name&#39;).asc()<br>&gt;&gt;&gt; Car.objects.all().order_by(&#39;name&#39;).desc()</pre><pre>SELECT &quot;inventory_car&quot;.&quot;id&quot;, &quot;inventory_car&quot;.&quot;name&quot;, &quot;inventory_car&quot;.&quot;factory&quot;, &quot;inventory_car&quot;.&quot;year&quot; <br>FROM &quot;inventory_car&quot; <br>ORDER BY &quot;inventory_car&quot;.&quot;name&quot; ASC</pre><p>👉 reverse() — allows to reverse the order in which a queryset’s elements are returned.</p><pre>&gt;&gt;&gt; q = Car.objects.all().order_by(&#39;name&#39;)<br>&gt;&gt;&gt; q.reverse()<br><br># To get last 5 elements<br>&gt;&gt;&gt; l5 = q.reverse()[:5]</pre><pre>SELECT &quot;inventory_car&quot;.&quot;id&quot;, &quot;inventory_car&quot;.&quot;name&quot;, &quot;inventory_car&quot;.&quot;factory&quot;, &quot;inventory_car&quot;.&quot;year&quot; <br>FROM &quot;inventory_car&quot; <br>ORDER BY &quot;inventory_car&quot;.&quot;name&quot; DESC<br><br>-- Just changes ASC to DESC</pre><p>👉 distinct() — used to eliminate duplicate objects.</p><pre>&gt;&gt;&gt; Car.objects.distinct()<br>&gt;&gt;&gt; Car.objects.order_by(&#39;name&#39;).distinct(&#39;name&#39;)</pre><pre>SELECT DISTINCT &quot;inventory_car&quot;.&quot;id&quot;, &quot;inventory_car&quot;.&quot;name&quot;, &quot;inventory_car&quot;.&quot;factory&quot;, &quot;inventory_car&quot;.&quot;year&quot; <br>FROM &quot;inventory_car&quot; <br>ORDER BY &quot;inventory_car&quot;.&quot;name&quot; ASC</pre><p>👉 values() — is used to specify which fields of the model you want to retrieve.</p><pre>&gt;&gt;&gt; Car.objects.values(&#39;name&#39;, &#39;factory&#39;)</pre><pre>SELECT &quot;inventory_car&quot;.&quot;id&quot;, &quot;inventory_car&quot;.&quot;name&quot;, &quot;inventory_car&quot;.&quot;factory&quot;<br>FROM &quot;inventory_car&quot;</pre><p>👉 dates() — returns a list of unique dates within a given queryset, based on the specified field.</p><pre>&gt;&gt;&gt; queryset = MyModel.objects.dates(&#39;date_field&#39;, &#39;month&#39;)</pre><pre>SELECT DISTINCT DATE_TRUNC(&#39;month&#39;, date_field) AS date_field<br>FROM myapp_mymodel;</pre><p>👉 datetimes() — similar to .dates(), but operates on datetime fields instead of date fields.</p><pre>&gt;&gt;&gt; queryset = MyModel.objects.datetimes(&#39;datetime_field&#39;, &#39;month&#39;, tzinfo=timezone.utc)</pre><pre>SELECT DISTINCT DATE_TRUNC(&#39;month&#39;, datetime_field AT TIME ZONE &#39;UTC&#39;) AS datetime_field<br>FROM myapp_mymodel;</pre><p>👉 union() — combines 2 or more querysets and returns their union.</p><pre>&gt;&gt;&gt; q1 = Car.objects.filter(year=2020)<br>&gt;&gt;&gt; q2 = Car.objects.filter(year=2010)<br>&gt;&gt;&gt; union = q1.union(q2)</pre><pre>(SELECT &quot;inventory_car&quot;.&quot;year&quot; FROM &quot;inventory_car&quot;.&quot;year&quot; WHERE &quot;inventory_car&quot;.&quot;year&quot; = 2020)<br>UNION<br>(SELECT &quot;inventory_car&quot;.&quot;year&quot; FROM &quot;inventory_car&quot;.&quot;year&quot; WHERE &quot;inventory_car&quot;.&quot;year&quot; = 2010)</pre><p>👉 intersection() — returns a queryset containing the intersection of the results of two querysets.</p><pre>&gt;&gt;&gt; q1 = Car.objects.filter(year=2020)<br>&gt;&gt;&gt; q2 = Car.objects.filter(year=2010)<br>&gt;&gt;&gt; intersect = q1.intersection(q2)</pre><pre>(SELECT &quot;inventory_car&quot;.&quot;year&quot; FROM &quot;inventory_car&quot;.&quot;year&quot; WHERE &quot;inventory_car&quot;.&quot;year&quot; = 2020)<br>INTERSECT<br>(SELECT &quot;inventory_car&quot;.&quot;year&quot; FROM &quot;inventory_car&quot;.&quot;year&quot; WHERE &quot;inventory_car&quot;.&quot;year&quot; = 2010)</pre><p>👉 difference() — returns a queryset containing the elements that are in the first queryset but not in the second queryset.</p><pre>&gt;&gt;&gt; q1 = Car.objects.filter(year=2020, factory=&quot;BYD&quot;)<br>&gt;&gt;&gt; q2 = Car.objects.filter(factory=&quot;BYD&quot;)<br>&gt;&gt;&gt; diff = q1.difference(q2)</pre><pre>(SELECT &quot;inventory_car&quot;.&quot;year&quot; FROM &quot;inventory_car&quot;.&quot;year&quot; WHERE &quot;inventory_car&quot;.&quot;year&quot; = 2020)<br>EXCEPT<br>(SELECT &quot;inventory_car&quot;.&quot;year&quot; FROM &quot;inventory_car&quot;.&quot;year&quot; WHERE &quot;inventory_car&quot;.&quot;year&quot; = 2010)</pre><p>👉 select_related() —</p><pre>&gt;&gt;&gt; Car.objects.select_related()</pre><pre>-- Alternative SQL query: Soon</pre><p>👉 prefetch_related() —</p><pre>&gt;&gt;&gt; Car.objects.prefetch_related()</pre><pre>-- Alternative SQL query: Soon</pre><p>👉 extra() — sometimes, the Django query syntax by itself can’t easily express a complex <strong>WHERE</strong> clause. In such cases, we can use this method for injecting specific clauses into SQL generated by a QuerySet.</p><pre>&gt;&gt;&gt; Car.objects.extra(where = [&quot;name = %s&quot;], params = [&#39;Kia&#39;])</pre><pre>SELECT *<br>FROM inventory_car<br>WHERE factory = &#39;Kia&#39;;</pre><p>👉 defer() — in some complex data-modeling situations, your models might contain a lot of fields, some of which could contain a lot of data (for example, text fields), or require expensive processing to convert them to Python objects. If you are using the results of a queryset in some situation where you don’t know if you need those particular fields when you initially fetch the data, you can tell Django not to retrieve them from the database.</p><pre>&gt;&gt;&gt; Car.objects.defer(&quot;description&quot;)<br># Car description is relatively long text ans it may not be necessary at initial fetching of the data</pre><pre>SELECT &quot;id&quot;, &quot;field3&quot;, &quot;field4&quot;  -- Excluding &#39;field1&#39; and &#39;field2&#39;<br>FROM myapp_mymodel;</pre><p>👉 only() — is used to retrieve only specific fields from the database, excluding all other fields.</p><pre>&gt;&gt;&gt; Car.objects.only(&quot;factory&quot;)</pre><pre>SELECT name FROM Car</pre><p>👉 Boolean operations: AND (&amp;), OR (|), XOR (^) are also supported in QuerySet management.</p><pre>&gt;&gt;&gt; Car.objects.filter(year=2010) &amp; Car.objects.filter(year=2020)<br>&gt;&gt;&gt; Car.objects.filter(year=2010) | Car.objects.filter(year=2020)<br>&gt;&gt;&gt; Car.objects.filter(year=2010) ^ Car.objects.filter(year=2020)</pre><p>👉 get() — retrieves a single object from the database that matches the given query parameters.</p><pre>&gt;&gt;&gt; Car.objects.get(year=2018)</pre><pre>SELECT * FROM Car WHERE year = 2018;</pre><p>👉 create() — creates a new object instance and saves it to the database in a single step.</p><pre>&gt;&gt;&gt; Car.objects.create(name=&quot;Sorento&quot;, factory=&quot;Kia&quot;, year=2023)</pre><pre>INSERT INTO Car(name, factory, year) VALUES (&#39;Sorento&#39;, &#39;Kia&#39;, 2023);</pre><p>👉 get_or_create() — retrieves an object if it exists based on the provided query parameters, otherwise creates a new object with those parameters.</p><pre>&gt;&gt;&gt; Car.objects.get_or_create(name=&quot;Sorento&quot;, factory=&quot;Kia&quot;, year=2023)</pre><pre>-- I think, there is no exact SQL equivalent</pre><p>👉 bulk_create() — inserts multiple objects into the database in a single query, which can be more efficient than saving each object individually.</p><pre>&gt;&gt;&gt; Car.objects.bulk_create(<br>  [<br>    Car(name=&quot;K5&quot;, factory=&quot;Kia&quot;, year=2021),<br>    Car(name=&quot;K8&quot;, factory=&quot;Kia&quot;, year=2023),<br>  ]<br>)</pre><pre>INSERT INTO Car <br>VALUES (&quot;K5&quot;, &quot;Kia&quot;, 2021), (&quot;K8&quot;, &quot;Kia&quot;, 2023);</pre><p>👉 count() — returns the number of objects in the database.</p><pre>&gt;&gt;&gt; Car.objects.count()</pre><pre>SELECT COUNT(*) FROM Car</pre><p>👉 in_bulk() — takes a list of field values (id_list) and the field_name for those values, and returns a dictionary mapping each value to an instance of the object with the given field value.</p><pre>&gt;&gt;&gt; Car.objects.in_bulk([1,2,3])<br>&gt;&gt;&gt; Car.objects.in_bulk([1,2,3], field_name=&quot;name&quot;)</pre><pre>SELECT * FROM Car WHERE id IN (1, 2, 3);<br>-- OR<br>SELECT name FROM Car WHERE id IN (1, 2, 3);</pre><p>👉 latest() — retrieves the latest object based on the specified field.</p><pre>&gt;&gt;&gt; Car.objects.latest(&#39;year&#39;)</pre><pre>SELECT * FROM Car ORDER BY year DESC LIMIT 1;</pre><p>👉 earliest() — retrieves the earliest object based on the specified field.</p><pre>&gt;&gt;&gt; Car.objects.earliest(&#39;year&#39;)</pre><pre>SELECT * FROM Car ORDER BY year ASC LIMIT 1;</pre><p>👉 first() — retrieves the first object in the queryset, according to the order of objects as they are stored in the database.</p><pre>&gt;&gt;&gt; Car.objects.first()</pre><pre>SELECT * FROM Car LIMIT 1;</pre><p>👉 last() — retrieves the last object in the queryset, according to the order of objects as they are stored in the database.</p><pre>&gt;&gt;&gt; Car.objects.last()</pre><pre>SELECT * FROM Car ORDER BY id DESC LIMIT 1;</pre><p>👉 exists() — checks if there are any objects that match the given query parameters.</p><pre>&gt;&gt;&gt; Car.objects.get(id=2).exists()</pre><pre>SELECT * FROM Car WHERE EXISTS id=2;</pre><p>👉 contains() — is used to check object membership in a QuerySet.</p><pre>&gt;&gt;&gt; queryset.contains(object)</pre><pre>-- There is not exact representation in SQL</pre><p>👉 update() — updates the fields of the objects that match the given query parameters with the provided values in a single database query.</p><pre>&gt;&gt;&gt; Car.objects.get(id=2).update(name=&quot;K5&quot;)</pre><pre>UPDATE Car SET name = &#39;K5&#39;;</pre><p>👉 delete() — deletes the objects that match the given query parameters from the database in a single database query.</p><pre>&gt;&gt;&gt; Car.objects.get(id=5).delete()</pre><pre>DELETE * FROM Car WHERE id=5;</pre><p>👉 explain() — generates an explanation of the query plan for the given queryset. This is useful for analyzing the performance of the query and identifying potential optimizations.</p><pre>&gt;&gt;&gt; Car.objects.all().explain()</pre><pre>EXPLAIN SELECT * FROM Car;</pre><p>There are so many methods in Django QuerySet API that we haven’t seen all of them yet. But at this point, I gave enough information in terms of equivalent SQL queries. At least I hope.</p><p><em>🏁 Yes, some methods are missing and maybe they can also be represented in SQL somehow. But now I cannot express them, yet in the future I can fix them. Thanks for your attention!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=457a916f244c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/django-unleashed/django-queryset-api-reference-alternative-sql-queries-for-each-method-457a916f244c">Django QuerySet API reference: alternative SQL queries for each method</a> was originally published in <a href="https://medium.com/django-unleashed">Django Unleashed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>