TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Django Styleguide

177 pointsby r4victorover 2 years ago

16 comments

olauover 2 years ago
I think there are too many concepts in this, but rather than being negative, here are some tips:<p>Always keep your models slim. Don&#x27;t stuff template related stuff in there. You need to look at those models often, so compact is a win. course_has_finished(course) is not much longer than course.has_finished(), and will allow you to expand the functionality as time goes on. Do precomputation if you need the information in a template - that keeps your templates simpler and allows you to easily expand the complexity of the precomputation.<p>Don&#x27;t use class-based views, at least not outside very specific niches like the Django admin. Class-based views will transform a simple, composeable call stack into a ball of inheritance mud. Inheritance is not a good code reuse tool.<p>Don&#x27;t make separate apps in the same project, unless the project actually consists of several different, completely independent projects. You can make subdirectories without making apps, and thus avoid dependency hell.<p>Also be wary of the formerly South, now built-in migrations stuff. It&#x27;s built around a fragile model (perfect history representation), so has lots of foot guns.<p>And be wary of 3rd party libraries with their own models. You can spend a lot of time trying to built bridges to those models compared to just doing what makes sense for your particular project. I think 3rd party libraries are perhaps best implemented without concrete models - duck-typing in Python let us do this. This includes Django itself, by the way. User profiles didn&#x27;t become good until Django allowed you to define the user model yourself.
评论 #34342729 未加载
评论 #34340731 未加载
评论 #34339479 未加载
评论 #34345528 未加载
评论 #34339701 未加载
评论 #34340044 未加载
评论 #34339658 未加载
评论 #34339913 未加载
评论 #34338940 未加载
评论 #34347042 未加载
评论 #34338756 未加载
评论 #34339274 未加载
评论 #34339089 未加载
评论 #34341629 未加载
j4mieover 2 years ago
I&#x27;ve been heavily inspired by this styleguide over the years, but I still think it&#x27;s a bit too complex. A few random thoughts:<p><pre><code> - I think &quot;services&quot; is too much of a loaded term. I prefer &quot;actions&quot;, and I always use the function-based style. - I hate the naming of &quot;APIs&quot; in this document. They use the term &quot;API&quot; when they mean &quot;endpoint&quot; or &quot;view&quot;. - &quot;Reuse serializers as little as possible&quot; is the single best piece of advice when using DRF. The inline InputSerializer thing is brilliant. - Having each each endpoint only handle a single HTTP verb is brilliant. - URLs and views should be separate from all other business logic (models, actions etc). - For read endpoints and associated business logic, I&#x27;d encourage https:&#x2F;&#x2F;www.django-readers.org&#x2F; (disclaimer: I&#x27;m the author).</code></pre>
评论 #34345817 未加载
评论 #34339961 未加载
hbrnover 2 years ago
Ah, the typical &quot;where to put business logic in Django&quot;.<p>M in ActiveRecord MVC web frameworks is deeply misunderstood. M is not &quot;data model&quot; (it would be called DVC if that was the case). M is your <i>domain</i> model. It&#x27;s the model of your business, model of the real world. It&#x27;s the core of your application.<p>Another thing that I never understood, why are functions called services? Is it a subconscious desire to go back to enterprisey kingdom of nouns? (apparently it is [1])<p>A service is either something that lives on a network (e.g. database, payment gateway, microservice). Or a class that has a state. Your functions are neither of those, they are just functions.<p>You business logic should live in the &quot;models&quot; namespace. Whether you put it on Model classes, or onto custom Managers, or just dump them into the module is not important, as long as you keep it consistent and keep your apps fairly small and isolated from each other.<p>Django already gives you enough tools to support big &quot;enterprise&quot; applications. It is far from perfect, but you&#x27;ll get much further if you embrace the framework instead of fighting it.<p>If you really are attached to this &quot;services&quot; mindset then Django API Domains [2] is your best option.<p>[1] <a href="https:&#x2F;&#x2F;www.b-list.org&#x2F;weblog&#x2F;2020&#x2F;mar&#x2F;16&#x2F;no-service&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.b-list.org&#x2F;weblog&#x2F;2020&#x2F;mar&#x2F;16&#x2F;no-service&#x2F;</a><p>[2] <a href="https:&#x2F;&#x2F;github.com&#x2F;phalt&#x2F;django-api-domains">https:&#x2F;&#x2F;github.com&#x2F;phalt&#x2F;django-api-domains</a>
评论 #34339804 未加载
评论 #34340187 未加载
andybakover 2 years ago
&gt; We use Celery for the following general cases:<p>&gt;<p>&gt; Communicating with 3rd party services (sending emails, notifications, etc.)<p>&gt; Offloading heavier computational tasks outside the HTTP cycle.<p>&gt; Periodic tasks (using Celery beat)<p>Sigh. No mention of the trade-offs. There&#x27;s simpler ways to do all these things. Celery is a big complex beast and it always pains me to see it as the default suggestion for simple tasks.
评论 #34338619 未加载
评论 #34343919 未加载
评论 #34338469 未加载
评论 #34338308 未加载
评论 #34339758 未加载
评论 #34345872 未加载
评论 #34339519 未加载
评论 #34338307 未加载
KyeRussellover 2 years ago
I have a long-running thread on the Django forums with a bunch of opinions about this topic: <a href="https:&#x2F;&#x2F;forum.djangoproject.com&#x2F;t&#x2F;structuring-large-complex-django-projects-and-using-a-services-layer-in-django-projects&#x2F;1487" rel="nofollow">https:&#x2F;&#x2F;forum.djangoproject.com&#x2F;t&#x2F;structuring-large-complex-...</a>
spapas82over 2 years ago
In a similar fashion, for anybody interested I&#x27;ve written some of my guidelines on implementing Django apps: <a href="https:&#x2F;&#x2F;www.spapas.net&#x2F;2022&#x2F;09&#x2F;28&#x2F;django-guidelines&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.spapas.net&#x2F;2022&#x2F;09&#x2F;28&#x2F;django-guidelines&#x2F;</a>
greenSunglassover 2 years ago
I&#x27;ve been working on a project with flask + sqlalchemy. I have those sql queries returning a bit of rows (up to 20k) and that are quite slow. SQLalchemy does not seem to support caching the results and I&#x27;ve started to use flask-caching[1] with redis using the @cache.memoize() decorator.<p>Just wondering if I am taking the right path or if there is better alternative.<p>[1]<a href="https:&#x2F;&#x2F;flask-caching.readthedocs.io" rel="nofollow">https:&#x2F;&#x2F;flask-caching.readthedocs.io</a>
评论 #34344248 未加载
评论 #34339699 未加载
评论 #34340961 未加载
Rastonburyover 2 years ago
I found this useful being someone who was self taught django and hacked together a project with no idea of architecture. To this day I don&#x27;t even know what a selector is referring to lol never used it<p>I&#x27;m learning node now for another mini project, is there anything similar? I know how it achieve certain tasks but to structure in a proper way I know nothing, all tutorials I&#x27;ve done never really go that deep
cproctorover 2 years ago
I&#x27;ve found it helpful in several projects to implement the &quot;services layer&quot; described here as a state machine, modeling state transitions for a central object (e.g. an article can be drafted, submitted, reviewed, published). The state machine enforces permissible transitions and handles side effects which touch other models.
chairmanwow1over 2 years ago
HN comments are really disparaging, but after reading through I really liked the content and am going to pull out their service &#x2F; serializer model to use in my project. Nice opinionated way to avoid structuring a program in a bad way.
zenith035over 2 years ago
Don&#x27;t create apps just for the sake of project structure even when models from multiple apps are closely related.<p>Moving models from one app to another is doable but it is a pain. It&#x27;s even worse if you are relying on GFKs.
OgAstorgaover 2 years ago
Somewhat off-topic but django is fundraising over here <a href="https:&#x2F;&#x2F;www.djangoproject.com&#x2F;fundraising&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.djangoproject.com&#x2F;fundraising&#x2F;</a>
radoslav_over 2 years ago
Hello everyone,<p>Radoslav here (one of the authors of the mentioned Django Styleguide).<p>First of all - I want to thank everyone to the comments The fact that someone took the time to read the styleguide &amp; then write a comment &#x2F; propose a different POV - is humbling.<p>I&#x27;ve read everything once &amp; I&#x27;ll do so at least couple more times. There are interesting ideas &amp; comments that we can apply!<p>And finally, I want to add some more context:<p>1. That particular styleguide has served us, and it&#x27;s still serving us well. It&#x27;s basically a list of ideas that we found useful, thanks to the various Django projects that we&#x27;ve been exposed to at HackSoft.<p>2. One core philosophy of the style guide is the ability to cherry-pick whatever makes sense to you. Even at our company, it&#x27;s very rare to have 2 Django projects following the exact same structure. The styleguide is rather a framework &#x2F; direction for things that&#x27;s been proven to work, from our experience.<p>3. And of course, the styleguide can use some more love from us. We are sitting on a lot of unshared knowledge that needs to be structured and applied back to the Django Styleguide &amp; the corresponding Django Styleguide example project.<p>4. We try to keep it pragmatic, so you can actually build something. For example, DDD sounds great, but lacks pragmatism and slows you down by a lot (at least, for us).<p>5. And finally - this is not the &quot;only right way&quot; to do Django. As there is no &quot;right way&quot; to build software. Luckily, there are always options. We&#x27;ll update the list of other suggested approaches, so people can have a choice &#x2F; navigate the space better.<p>As an example of one of the big topics that we want to touch upon is nesting apps. Alongside the &quot;services &#x2F; selectors&quot; layer (btw - you can call this whatever suits you best ), the ability to nest apps within apps is really powerful, when it comes to the structure and longevity of a Django project. Having 50+ flat apps is not the best experience.<p>Our current focus is around building the company (HackSoft). The Django Styleguide will be soon to follow. We are slowly gaining more speed &amp; we&#x27;ll eventually get there<p>All discussion around &quot;How to do Django&quot; are in fact really interesting. If we happen to meet at some future EuroPython &#x2F; DjangoCon Europe - I&#x27;m always open to discuss in person. Otherwise, if you have specific comments &#x2F; suggestions - you can submit it either as an issue &#x2F; discussion, or just send an email to radorado@hacksoft.io<p>Cheers!
评论 #34424917 未加载
drcongoover 2 years ago
Can&#x27;t believe they&#x27;re putting `class Meta` at the bottom of models.
评论 #34338098 未加载
theptipover 2 years ago
On testing, I think &quot;one file &amp; class per thing-to-test&quot; is subtly bad advice. It&#x27;s not harmful in the hands of someone that knows what they are doing, but it tends to point engineers towards a tightly-coupled test suite, which ends up making refactoring more painful and error prone down the road.<p>If you have one testclass per entity, then if you make any changes to the structure of your services&#x2F;models&#x2F;entities, you must restructure your tests too. This means you can&#x27;t do the &quot;dream refactor&quot; where you don&#x27;t touch your tests, and restructure your code without changing any behavior. If you rewrite your tests whenever your structure changes, how can you be sure you&#x27;ve not broken your tests?<p>Instead, I advocate for testing behaviors. In a tightly-integrated framework like Django, most of your tests are going to be integration tests (i.e. you have a database involved). You should bias those tests towards an integration-y approach that uses the public interfaces (Service Layer, if you have one) and asserts behavior. Ideally the tests should not change if the business logic has not changed. (In practice you&#x27;ll often need to add some mapping&#x2F;helper&#x2F;setup code to make this true.)<p>If you have any fat-model type behavior that is explicitly scoped to a single model, then you can test that in isolation. Many Django projects call these &quot;unit tests&quot; even though they still involve reading and writing your model from the DB. I call them &quot;focused integration tests&quot;. All that matters is that you have agreement on terminology inside your project. If you have extremely complex domain logic, it can be worthwhile to construct &quot;true Unit Tests&quot; that use dummy objects to test logic without hitting your DB. I&#x27;ve not found it worthwhile to mock the DB in most Django projects though.<p>To provide an example of where my &quot;test behaviors not classes&quot; advice differs from the OP&#x27;s paradigm, let&#x27;s say you split out a sub-object to provide a pluggable Strategy for a part of your Model&#x27;s behavior -- you don&#x27;t necessarily need to have detailed tests for that Strategy class if it&#x27;s fully covered by the model&#x27;s tests. Only the edge cases that are awkward to test at the higher level need to be tested at the granular level of the Strategy. Indeed, the first refactor that just creates a Strategy holding your existing behavior need not change any of your existing tests at all! Indeed, if you do need to change existing tests, that suggests your tests were improperly-coupled to the code under test, since a mere structural change like this should not affect the behavior of your application. Even after adding more Strategy logic, most of your old ModelTests are still good; they still test the high-level behavior, and now also test the integration between your model and the new Strategy class. Basically, test at the most-granular level that gives a clear, decoupled test for your behavior; resist testing every entity in isolation, because some entities have rich coreographies with other entites that make them hard to isolate. Sometimes you have to contort and tightly-couple in order to test things at the very-lowest-level possible.<p>Inspiration&#x2F;further reading: <a href="https:&#x2F;&#x2F;blog.cleancoder.com&#x2F;uncle-bob&#x2F;2017&#x2F;10&#x2F;03&#x2F;TestContravariance.html" rel="nofollow">https:&#x2F;&#x2F;blog.cleancoder.com&#x2F;uncle-bob&#x2F;2017&#x2F;10&#x2F;03&#x2F;TestContrav...</a>. (Grit your teeth through the &quot;Socratic dialog&quot; style. The principle being described is extremely valuable.)
warinukraineover 2 years ago
I hate making webpages, but Django makes it as bearable as it can be.<p>I hate python, but love Django.<p>I think I have some sort of emotional attachment to Django.