Advanced Django Models: Improve Your Python Development

Advanced Django Models: Improve Your Python Development

Master Django models, a core concept of the popular web framework. Dive into advanced topics, like how the Active Record pattern works for Django’s ORM systems

Models are a core concept of the Django framework. According to Django’s design philosophies for models, we should be as explicit as possible with the naming and functionality of our fields, and ensure that we’re including all relevant functionality related to our model in the model itself, rather than in the views or somewhere else. If you’ve worked with Ruby on Rails before, these design philosophies won’t seem new as both Rails and Django implement the Active Record pattern for their object-relational mapping (ORM) systems to handle stored data.

In this post we’ll look at some ways to leverage these philosophies, core Django features, and even some libraries to help make our models better.

getter/setter/deleter properties

As a feature of Python since version 2.2, a property’s usage looks like an attribute but is actually a method. While using a property on a model isn’t that advanced, we can use some underutilized features of the Python property to make our models more powerful.

If you’re using Django’s built-in authentication or have customized your authentication using AbstractBaseUser, you’re probably familiar with the last_login field defined on the User model, which is a saved timestamp of the user’s last login to your application. If we want to use last_login, but also have a field named last_seen saved to a cache more frequently, we could do so pretty easily.

First, we’ll make a Python property that finds a value in the cache, and if it can’t, it returns the value from the database.

accounts/models.py
from django.contrib.auth.base_user import AbstractBaseUser
from django.core.cache import cache


class User(AbstractBaseUser):
    ...
    
    @property
    def last_seen(self):
        """
        Returns the 'last_seen' value from the cache for a User.
        """
        last_seen = cache.get('last_seen_{0}'.format(self.pk))

        # Check cache result, otherwise return the database value
        if last_seen:
            return last_seen

        return self.last_login

Note: I’ve slimmed the model down a bit as there’s a separate tutorial on this blog about specifically customizing the built-in Django user model.

The property above checks our cache for the user’s last_seen value, and if it doesn’t find anything, it will return the user’s stored last_login value from the model. Referencing <instance>.last_seen now provides a much more customizable attribute on our model behind a very simple interface.

We can expand this to include custom behavior when a value is assigned to our property (some_user.last_seen = some_date_time), or when a value is deleted from the property (del some_user.last_seen).

...
    
@last_seen.setter
def last_seen(self, value):
    """
    Sets the 'last_seen_[uuid]' value in the cache for a User.
    """
    now = value

    # Save in the cache
    cache.set('last_seen_{0}'.format(self.pk), now)

@last_seen.deleter
def last_seen(self):
    """
    Removes the 'last_seen' value from the cache.
    """
    # Delete the cache key
    cache.delete('last_seen_{0}'.format(self.pk))
    
...

Now, whenever a value is assigned to our last_seen property, we save it to the cache, and when a value is removed with del, we remove it from the cache. Using setter and deleter is described in the Python documentation but is rarely seen in the wild when looking at Django models.

You may have a use case like this one, where you want to store something that doesn’t necessarily need to be persisted to a traditional database, or for performance reasons, shouldn’t be. Using a custom property like the above example is a great solution.

In a similar use case, the python-social-auth library, a tool for managing user authentication using third-party platforms like GitHub and Twitter, will create and manage updating information in your database based on information from the platform the user logged-in with. In some cases, the information returned won’t match the fields in our database. For example, the python-social-auth library will pass a fullname keyword argument when creating the user. If, perhaps in our database, we used full_name as our attribute name then we might be in a pinch.

A simple way around this is by using the getter/setter pattern from above:

@property
def fullname(self) -> str:
    return self.full_name

@fullname.setter
def fullname(self, value: str):
    self.full_name = value

Now, when python-social-auth saves a user’s fullname to our model (new_user.fullname = 'Some User'), we’ll intercept it and save it to our database field, full_name, instead.

through model relationships

Django’s many-to-many relationships are a great way of handling complex object relationships simply, but they don’t afford us the ability to add custom attributes to the intermediate models they create. By default, this simply includes an identifier and two foreign key references to join the objects together.

Using the Django ManyToManyField through parameter, we can create this intermediate model ourselves and add any additional fields we deem necessary.

If our application, for example, not only needed users to have memberships within groups, but wanted to track when that membership started, we could use a custom intermediate model to do so.

accounts/models.py
import uuid

from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
from django.utils.timezone import now


class User(AbstractBaseUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    …

class Group(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    members = models.ManyToManyField(User, through='Membership')

class Membership(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    joined = models.DateTimeField(editable=False, default=now)

In the example above, we’re still using a ManyToManyField to handle the relationship between a user and a group, but by passing the Membership model using the through keyword argument, we can now add our joined custom attribute to the model to track when the group membership was started. This through model is a standard Django model, it just requires a primary key (we use UUIDs here), and two foreign keys to join the objects together.

Using the same three model pattern, we could create a simple subscription database for our site:

import uuid

from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
from django.utils.timezone import now


class User(AbstractBaseUser):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ...

class Plan(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=50, unique=True, default='free')
    subscribers = models.ManyToManyField(User, through='Subscription', related_name='subscriptions', related_query_name='subscriptions')

class Subscription(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    created = models.DateTimeField(editable=False, default=now)
    updated = models.DateTimeField(auto_now=True)
    cancelled = models.DateTimeField(blank=True, null=True)

Here we’re able to track when a user first subscribed, when they updated their subscription, and if we added the code paths for it, when a user canceled their subscription to our application.

Using through models with the ManyToManyField is a great way to add more data to our intermediate models and provide a more thorough experience for our users without much added work.

Proxy models

Normally in Django, when you subclass a model (this doesn’t include abstract models) into a new class, the framework will create new database tables for that class and link them (via OneToOneField) to the parent database tables. Django calls this “multi-table inheritance” and it’s a great way to re-use existing model fields and structures and add your own data to them. “Don’t repeat yourself,” as the Django design philosophies state.

Multi-table inheritance example:

from django.db import models

class Vehicle(models.Model):
    model = models.CharField(max_length=50)
    manufacturer = models.CharField(max_length=80)
    year = models.IntegerField(max_length=4)

class Airplane(Vehicle):
    is_cargo = models.BooleanField(default=False)
    is_passenger = models.BooleanField(default=True)

This example would create ...

...continue with Proxy Models

Zac Clancy is Vice President at Global DIRT (Disaster Immediate Response Team)

ECommerce Mobile App Development | Ecommerce Mobile App Development Services

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates. **Know about [Top ECommerce Mobile App Development...

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates.

Know about Top ECommerce Mobile App Development Company

Is Low-code or no-code development is future of mobile app development

Is Low-code or no-code development is future of mobile app development

Mobile app development has skyrocketed over these years with the increasing demand of mobile apps for a variety of purposes like entertainment, banking, weather update, health, booking movie tickets, booking a taxi etc. With the latest...

Mobile app development has skyrocketed over these years with the increasing demand of mobile apps for a variety of purposes like entertainment, banking, weather update, health, booking movie tickets, booking a taxi etc. With the latest technologies adopted by mobile app development services, there are different app development approaches which are being practiced. Among them is low-code or no-code development. But will it be the future of mobile app development? Will any mobile application development company start taking this approach as the primary one. Let’s try to find a detailed answer to this question.

But first, let’s understand what this approach exactly is? Well, it is a streamlined approach which involves swift design as well as development with minimal coding, generally relying on different third-party APIs.

Even though there isn’t any single definition of no-code or low-code development because it is actually more of a mindset rather than something which can be directly measured, this mindset has certainly led to a vast community mushrooming up with this mentality. Android app development services are rapidly adopted by this approach. Low-code app innovators are rapidly disrupting all types of various industries. There are a plethora of benefits to these low code platforms and let’s look at this.

1. Less Number of Bugs

It is pretty evident that less code actually means fewer bugs. As simple as that. The entire bug testing phase is actually a major part of modern and latest application development. It is quite inevitable that various issues will come up if there is actually enough code present there. But the best thing regarding low code platforms is that there’s certainly less to test. Also, when they actually tap into APIs, those particular APIs are actually tested by other people.

Lesser number of bugs is better for both users, as well as developers since less amount of time, will be taken up with bug-fixes and troubleshooting. Also, the fast pace of this development approach actually means that if in any case a bug is found, it is generally better just to develop a new iteration rather than fixing it.

2. Significant Lower Costs

Among the most obvious reasons for why you would actually opt for any low code platform is that in reality, low code results in lower cost. Low code development leads to faster app development which saves a lot of time and as a result, lower cost.

It's not only good for companies but also for developers. It certainly cut out the intermediaries, and while they charge less, they use fewer resources and finally come out on top. It is fun for developers because it stops them from actually finding themselves stuck on one particular project which seems to last forever. This is why most of the companies hire app developer who is a well-versed with low-code development.

3. Better Accessibility

The lesser amount of code an application uses, the lesser bandwidth is needed to download it as well as run it. This is quite good news for the people who are based in rural areas or in different developing countries where access to the internet isn’t as prevalent as Western countries. Also, as low code applications can easily be created quite easily than a traditional app, they can easily be released much more swiftly and at a much lower price, and sometimes for free. iPhone app development services follow this approach because it will help in increasing the uptake of their apps as it reduces the entry barrier for every person from lower-income families.

Innovative Development Approach

Among the most promising instances of a low-code or no-code platform is Uber. The apps tap into Google for Maps, Dropbox for storage, Braintree for payments and much more. The most interesting thing about this is that app programming interfaces of APIs which Uber actually relies upon are easily available to anyone who wishes to use them. Uber took those APIs and then used them to create, which was new without requiring to develop each of those particular individual elements, all by themselves. They developed their own brand on top of it by means of looking at how they could actually differentiate themselves from the rest of the others. Mobile app development services should follow this example to create their own low code mobile app which disrupts the market.

The best thing about this is that it inspires innovation. At present, the marketplace actually decides, and only the best applications rise to the top. Also, low code development easily allows developers to iterate much more quickly and can aim for higher more.

The Role of Artificial Intelligence (AI)

Artificial Intelligence is certainly making big waves in different businesses, and as this technology improves further, it will find its way in different other uncharted areas. Among those areas is the low code app development, where it comes in quite useful for a wide range of tasks and actions including the integration of various data sources or just making sense of an entire unstructured or semi-structured data.

Artificial Intelligence is quite great at analysing and conducting trial and error. Hence, it won’t be quite long until the usage of AI becomes quite a standard part of the low code app development. A mobile application development company can find ways to reduce the total amount of code that it is using through AI and flagging potential and possible improvements.

Conclusion

It is quite certain that low-code or no-code app development is the future of app development for one of the simplest reasons that it is quite easier as well as faster and efficiently uses time. It actually doesn’t matter whether Android app development services or iPhone app development services are on-board with this particular change or not. This is quite inevitable as this approach is the path of least resistance. Also, as the inherent demand for low code platforms keeps in growing, developers will certainly find themselves to adopt it.

It is quite a great news as it will push the developers of mobile application development services to become the best. Also, there won’t be any time to redoing it to create the same thing, or any room for sloppy code as well as lengthy development processes which makes the mobile apps redundant even before they are actually finished. Hence, low-code or no-code development will certainly lead the future of mobile app development, and mobile app developers certainly have to get on the bandwagon, one way or the other.

Mobile App Development Company in USA

Mobile App Development Company in USA

**How [Mobile App Development Company in the USA](https://www.dataeximit.com/mobile-app-development-service/ "Mobile App Development Company in the USA"), can breathe life into Your Amazing Ideas?** Today’s Mobile world mobile apps become one of...

How Mobile App Development Company in the USA, can breathe life into Your Amazing Ideas?

Today’s Mobile world mobile apps become one of the important factors in each and every business whether it may be a product based company or a service-based company.

Data EximIT has a strong team of mobile app developers & programmers who have the qualifications and experience in developing apps across several platforms, including iOS, Android, and PhoneGap and. We give our clients complete flexibility with respect to cutting short or extending projects after the minimum term is complete.

Our Mobile App Development Services Are...

  • Android Application Development
  • iOS Application Development
  • Responsive Web Applications
  • Hybrid Mobile Application Development
  • Xamarin Application Development
  • Mobile UI/UX Design

Contact Our Experts For More Information