Skip to main content

Django Models Mixins

One thing I've been experimenting with is model Mixins.  For example, the aim is to create small abstract classes that are each focused around a particular function.  These abstract classes can then be added to arbitrary models to apply those functions to models as desired.

For example, say I define a RatingsFields abstract class and a TrackingFields abstract class.  These abstract classes can be mixed into any other model that we wish to add rating or tracking functionality to.

core/mixins.py
from djangoratings.fields import RatingField # 3rd party module

class RatingFields(models.Model):
    
    rating = RatingField(range=5) # 5 possible rating values, 1-5

    class Meta:
        abstract = True
        

class TrackingFields(models.Model):

    deleted_on = models.DateTimeField(blank=True, null=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True
        

Since we applied the abstract classes to the Post model below, the model now has rating and tracking capabilities.  This is useful to help simplify code where a lot of models share fields or methods with the same function.

myapp/models.py
from core import mixins as core_mixins
class Post(core_mixins.TrackingFields, core_mixins.RatingFields):
    name = models.CharField(max_length=128)
    slug = models.SlugField(max_length=128)
    ...

Comments welcome.
Joe

Comments

  1. Did you try django.contrib.contenttypes?

    ReplyDelete
  2. Thanks for your comment, Pavel. I've used content types and generic relations in the past and they are very useful.

    With this mixin approach, the fields are created on the given table rather than linked through a foreign key. This might be handy for situations where we know we are going to need the same fields on a given table - such as the TrackingFields - and want to avoid code duplication. Granted, this might reduce some of the flexibility that a generic relation would afford us, but perhaps also reduce some of the complexity.

    If you have other thoughts or suggestions regarding this, please feel free to share. I'm eager to learn of better approaches. Thank you again,
    Joe

    ReplyDelete
  3. Thanks Eduardo... core_interfaces is a copy-paste error. I've made the correction. Thank you for pointing that out.

    ReplyDelete
  4. Although this is a good example of using mixins, I wouldn't call this an example of aspect-orientated programming.

    ReplyDelete
  5. Thanks cody-somerville. Perhaps I was off on my naming. I'll adjust the title name.

    ReplyDelete
  6. I was trying to figure out the best way to do this (see http://stackoverflow.com/questions/6428075/is-it-ok-to-use-multiple-inheritance-with-django-abstract-models) , whether my Mixins needed to inherit from models.Model or not, and so forth. This is a good anwser.

    ReplyDelete
  7. Name and slug are very generic too, you could put them in a mixin...

    ReplyDelete
  8. keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
    digital marketing training in bangalore | https://www.excelr.com/digital-marketing-training-in-bangalore

    ReplyDelete
  9. As always your articles do inspire me. Every single detail you have posted was great. ExcelR Pune Digital Marketing Course

    ReplyDelete
  10. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
    Best Data Science training in Mumbai

    Data Science training in Mumbai

    ReplyDelete
  11. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
    SAP training in Kolkata
    SAP training Kolkata
    Best SAP training in Kolkata
    SAP course in Kolkata
    SAP training institute Kolkata

    ReplyDelete
  12. Truly incredible blog found to be very impressive due to which the learners who ever go through it will try to explore themselves with the content to develop the skills to an extreme level. Eventually, thanking the blogger to come up with such an phenomenal content. Hope you arrive with the similar content in future as well.
    Digital Marketing Course in Raipur

    ReplyDelete
  13. Kardinal Stick Siam - relx a great promotion. Express delivery in 3 hours.

    ufa football betting, casino, slots, lottery, direct website 1688, stable financial, 100% UFABET168.

    Online Baccarat FOXZ24 Easy to apply, fast, บาคาร่า deposit-withdraw 10 seconds with the system.

    Watch movies online sa-movie.com, watch new movies, series Netflix HD 4K ดูหนังออนไลน์, watch free movies on your mobile phone, Tablet, watch movies on the web.

    SEE4K Watch movies, watch movies, free series, load without interruption, sharp images in HD FullHD 4k, ดูหนังใหม่ all matters, all tastes, see anywhere, anytime, on mobile phones, tablets, computers.

    GangManga read manga, read manga, read manga online for free, fast loading, clear images in HD quality, อ่านการ์ตูน all titles, anywhere, anytime, on mobile, tablet, computer.

    Watch live football ผลบอลสด, watch football online, link to watch live football, watch football for free.

    ReplyDelete
  14. Stupendous blog huge applause to the blogger and hoping you to come up with such an extraordinary content in future. Surely, this post will inspire many aspirants who are very keen in gaining the knowledge. Expecting many more contents with lot more curiosity further.

    Data Science Certification in Bhilai

    ReplyDelete
  15. Extraordinary blog went amazed with the content that they have developed in a very descriptive manner. This type of content surely ensures the participants to explore themselves. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

    Data Science Training

    ReplyDelete
  16. I like your post. I appreciate your blogs because they are really good. Please go to this website for Data analyst course in Bangalore. These courses are wonderful for professionals.

    ReplyDelete
  17. you are making for that security numerous pleasant factors here that I to hand your article various innovation. Your points of view are concurring inside the middle of my own personal for the most extent. this is allowable substance in your perusers. Facebook Account Hacker Pro

    ReplyDelete
  18. for certain i'm absolutely in all honesty later this article and that I on a very basic level pulse broadcast that this flyer is totally conceivable and truely educational article.i will make obvious for look at your weblog more. You made an unadulterated lightening in any event can't designate dissipate to regardless bewilderment, what by and large the fresh out of the plastic new part? !!!!!!thanks. Birthday Wish For Sister

    ReplyDelete

Post a Comment

Popular posts from this blog

Docker: Run as non root user

It's good practice to run processes within a container as a non-root user with restricted permissions.  Even though containers are isolated from the host operating system, they do share the same kernel as the host. Also, processes within a container should be prevented from writing to where they shouldn't be allowed to as extra protection against exploitation. Running a Docker process as a non-root user has been a Docker feature as of version 1.10. To run a Docker process as a non-root user, permissions need to be accounted for meticulously.  This permission adjustment needs to be done when building a Dockerfile. You need to be aware of where in the filesystem your app might write to, and adjust the permissions accordingly.  Since everything in a container is considered disposable, the container process really shouldn't be writing to too many locations once build. Here is an annotated example of how you might create a Dockerfile where the process that runs within runs a

Django: Using Caching to Track Online Users

Recently I wanted a simple solution to track whether a user is online on a given Django site.  The definition of "online" on a site is kind of ambiguous, so I'll define that a user is considered to be online if they have made any request to the site in the last five minutes. I found that one approach is to use Django's caching framework to track when a user last accessed the site.  For example, upon each request, I can have a middleware set the current time as a cache value associated with a given user.  This allows us to store some basic information about logged-in user's online state without having to hit the database on each request and easily retrieve it by accessing the cache. My approach below.  Comments welcome. In settings.py: # add the middleware that you are about to create to settings MIDDLEWARE_CLASSES = ( .... 'middleware.activeuser_middleware.ActiveUserMiddleware' , .... ) # Setup caching per Django docs. In actuality, you

uWSGI Basic Django Setup

Here are two basic examples of almost the same uWSGI configuration to run a Django project; one is configured via an ini configuration file and the other is configured via a command line argument. This does not represent a production-ready example, but can be used as a starting point for the configuration. Setup for this example: # create dir for virtualenv and activate mkdir envs/ virtualenv envs/runrun/ . ./envs/runrun/bin/activate # create dir for project codebase mkdir proj/ # install some django deps pip install django uwsgi whitenose # create a new django project cd proj/ django-admin startproject runrun cd runrun/ # Add to or modify django settings.py to setup static file serving with Whitenoise. # Note: for prod environments, staticfiles can be served via Nginx. # settings.py  MIDDLEWARE_CLASSES = [     ....     'whitenoise.middleware.WhiteNoiseMiddleware', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE =