Fun with Django's New Postgres Features

For this post, we are going to focus on the user model and explore how Django’s new PostgreSQL features support the modeling.

Playaz Club?

Since I’m a huge geek and have no chance of ever getting into a real Playaz Club (and because back in the day 4 Tay was the bomb), I decided to build my own virtual online Playaz Club. What is that exactly? A private, invite-only social network targeted at a small group of like-minded individuals.

For this post, we are going to focus on the user model and explore how Django’s new PostgreSQL features support the modeling. The new features we are referring to are PostgreSQL-only, so don’t bother trying this unless you have your database ENGINE equal to django.db.backends.postgresql_psycopg2. You will need version >= 2.5 of psycopg2. Aight playa, let’s do this.

Holla if you with me! :)

Modeling a Playa’s Rep

Every playa got a rep, and they want the whole world to know about their rep. So let’s create a user profile (aka a “rep”) that allows for each of our playaz to express their individuality.

Here’s the basic model for a playaz rep:

from django.db import models
from django.contrib.auth.models import User

class Rep(models.Model):
    playa = models.OneToOneField(User)
    hood = models.CharField(max_length=100)
    area_code = models.IntegerField()

Nothing specific to 1.8 above. Just a standard model to extend the base Django User, cause a playa still needs a username and email address, right? Plus we added two new fields to store the playaz hood and area code.

Bankroll and the RangeField

For a playa, repping your hood ain’t always enough. Playaz often like to flaunt their bankroll, but at the same time don’t want to be letting people know exactly how large that bankroll is. We can model that with one of the new Postgres Range Fields. Of course we will use the BigIntegerRangeField to better model massive digits, amiright?

bankroll = pgfields.BigIntegerRangeField(default=(10, 100))

Range fields are based on the psycopg2 Range objects and can be used for Numeric and DateRanges. With the bankroll field migrated to the database, we can interact with our range fields by passing it a range object, so creating our first playa would look something like this:

>>> from playa.models import Rep
>>> from django.contrib.auth.models import User
>>> calvin = User.objects.create_user(username="snoop", password="dogg")
>>> calvins_rep = Rep(hood="Long Beach", area_code=213)
>>> calvins_rep.bankroll = (100000000, 150000000)
>>> calvins_rep.playa = calvin

Notice this line: calvins_rep.bankroll = (100000000, 150000000). Here we are setting a range field by using a simple tuple. It is also possible to set the value using a NumericRange object like so:

from psycopg2.extras import NumericRange
br = NumericRange(lower=100000000, upper=150000000)
calvin.rep.bankroll = br

This is essentially the same as using the tuple. However, it’s important to know about the NumericRange object as that is used to filter the model. For example, if we wanted to find all playas whose bankroll was greater than 50 million (meaning the entire bankroll range is greater than 50 million):

Rep.objects.filter(bankroll__fully_gt=NumericRange(50000000, 50000000))

And that will return the list of those playas. Alternatively, if we wanted to find all playas whose bankroll is “somewhere around the 10 to 15 million range”, we could use:

Rep.objects.filter(bankroll__overlap=NumericRange(10000000, 15000000))

This would return all playas that have a bankroll range that includes at least some part of the 10 to 15 million range. A more absolute query would be all playas that have a bankroll fully in between a range, i.e. everybody that’s making at least 10 million but not more than 15 million. That query would look like:

Rep.objects.filter(bankroll__contained_by=NumericRange(10000000, 15000000))

More information about Range-based queries can be found here.

Skillz as ArrayField

It ain’t all about the bankroll, playaz got skillz, all kinds of skillz. Let’s model those with an ArrayField.

skillz = pgfields.ArrayField(
    models.CharField(max_length=100, blank=True),
    blank = True,
    null = True,

To declare the ArrayField we have to give it a first argument, which is the basefield. Unlike Python lists, ArrayFields must declare each element of the list as the same type. Basefield declares which type this is, and it can be any of the standard model field types. In the case above, we have just used a CharField as our basetype, which means skillz will be an array of strings.

Storing values to the ArrayField is exactly as you expect:

>>> from django.contrib.auth.models import User
>>> calvin = User.objects.get(username='snoop')
>>> calvin.rep.skillz = ['ballin', 'rappin', 'talk show host', 'merchandizn']

Finding playas by skillz

If we need a particular playa with a particular skill, how we gonna find them? Use the __contains filter:


For playas who have any of the skills [‘rappin’, ‘djing’, ‘producing’] but no other skills, you could do a query like so:

Rep.objects.filter(skillz__contained_by=['rappin', 'djing', 'producing'])

Or if you want to find anyone that has any of a certain list of skills:

Rep.objects.filter(skillz__overlap=['rappin', 'djing', 'producing'])

You could even find only those people who listed a skill as their first skill (because everybody lists their best skill first):


Game as HStore

Game can be thought of as a list of miscellaneous, random skills a playa might have. Since Game spans all kinds of things, let’s model it as an HStore field, which basically means we can stick any old Python dictionary in there:

game = pgfields.HStoreField()

Take a second to think about what we just did here. HStore is pretty huge. It basically allows for “NoSQL”-type data storage, right inside of postgreSQL. Plus, since it’s inside PostgreSQL we can link (through foreign keys), tables that contain NoSQL data with tables that store regular SQL-type data. You can even store both in the same table on different columns as we are doing here. Maybe playas don’t need to use that jankie, all-talk MongoDB anymore…
Coming back to implementation details, if you try to migrate the new HStore field into the database and end up with this error-

django.db.utils.ProgrammingError: type "hstore" does not exist

-then your PostgreSQL database is pre 8.1 (time to upgrade, playa) or doesn’t have the HStore extension installed. Keep in mind that in PostgreSQL the HStore extension is installed per database and not system-wide. To install it from your psql prompt, run the following SQL:


Or if you want, you could do it through a SQL Migration with the following migration file (assuming you were connected to the database as the superuser):

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.RunSQL("CREATE EXTENSION IF NOT EXISTS hstore")

Finally, you will also need to make sure that you have added 'django.contrib.postgres' to 'settings.INSTALLED_APPS' to make use of HStore fields.

With that setup we can add data to our HStoreField game by throwing a dictionary at it like so:

>>> calvin = User.objects.get(username="snoop")
>>> = {'best_album': 'Doggy Style', 'youtube-channel': \
    '', 'twitter_follows' : '11000000'}

Do keep in mind that the dict must only use strings for all keys and values.

And now for some more interesting examples…


Let’s write a “show game” function to search the playaz game and return a list of playaz that match. In geeky terms, we’re searching through the HStore field for any keys passed into the function. It looks something like this:

def show_game(key):
    return Rep.Objects.filter(game__has_key=key).values('game','playa__username')

Above we have used the has_key filter for the HStore field to return a queryset, then further filtered it with the values function (mainly to show that you can chain django.contrib.postgres stuff with regular query set stuff).

The return value would be a list of dictionaries:

  {'playa__username': 'snoop',
  'game': {'twitter_follows': '11000000',
           'youtube-channel': '',
           'best_album': 'Doggy Style'

As they say, Game recognizes Game, and now we can search for game, too.

High Rollers

If we believe what the playaz are telling us about their bankrolls, then we can use that to rank them in categories (since it’s a range). Let’s add a Playa ranking based upon the bankroll with the following levels:

  • young buck – bankroll less than one hundred grand
  • balla – bankroll between 100,000 and 500,000 with the skill ‘ballin’
  • playa – bankroll between 500,000 and 1,000,000 with two skillz and some game
  • high roller – bankroll greater than 1,000,000
  • O.G. – has the skill ‘gangsta’ and game key “old-school”

The query for balla is below. This would be the strict interpretation, which would return only those whose entire bankroll range is within the specified limits:

Rep.objects.filter(bankroll__contained_by=[100000, 500000], skillz__contains=['ballin'])

Try out the rest yourself for some practice. If you need some help, Read the Docs.

#django #postgresql #database #web-development

What is GEEK

Buddha Community

Fun with Django's New Postgres Features
Ahebwe  Oscar

Ahebwe Oscar


Django admin full Customization step by step

Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register  and unregister  models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.


Custom Titles of Django Admin

Exclude in Django Admin

Fields in Django Admin

#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization

Ahebwe  Oscar

Ahebwe Oscar


How model queries work in Django

How model queries work in Django

Welcome to my blog, hey everyone in this article we are going to be working with queries in Django so for any web app that you build your going to want to write a query so you can retrieve information from your database so in this article I’ll be showing you all the different ways that you can write queries and it should cover about 90% of the cases that you’ll have when you’re writing your code the other 10% depend on your specific use case you may have to get more complicated but for the most part what I cover in this article should be able to help you so let’s start with the model that I have I’ve already created it.

**Read More : **How to make Chatbot in Python.

Read More : Django Admin Full Customization step by step

let’s just get into this diagram that I made so in here:

django queries aboutDescribe each parameter in Django querset

we’re making a simple query for the myModel table so we want to pull out all the information in the database so we have this variable which is gonna hold a return value and we have our myModel models so this is simply the myModel model name so whatever you named your model just make sure you specify that and we’re gonna access the objects attribute once we get that object’s attribute we can simply use the all method and this will return all the information in the database so we’re gonna start with all and then we will go into getting single items filtering that data and go to our command prompt.

Here and we’ll actually start making our queries from here to do this let’s just go ahead and run** Python shell** and I am in my project file so make sure you’re in there when you start and what this does is it gives us an interactive shell to actually start working with our data so this is a lot like the Python shell but because we did it allows us to do things a Django way and actually query our database now open up the command prompt and let’s go ahead and start making our first queries.

#django #django model queries #django orm #django queries #django query #model django query #model query #query with django

4 key Features of Django Framework that Make it the Best Amongst all!

Django is one of the popular python based open-source web frameworks mainly used by the developers who like to have rapid development along with the clean pragmatic design.

Read this blog to know the various Django Features with details.

#django framework #django web development #django development company #django development services #python django development company #python django development

Ahebwe  Oscar

Ahebwe Oscar


Basic and Full-text Search with Django and Postgres

Unlike relational databases, full-text search is not standardized. There are a number of open-source options like ElasticSearch, Solr, and Xapian. ElasticSearch is probably the most popular solution; however, it’s complicated to set up and maintain. Further, if you’re not taking advantage of some of the advanced features that ElasticSearch offers, you should stick with the full-text search capabilities that many relational (like Postgres, MySQL, SQLite) and non-relational databases (like MongoDB and CouchDB) offer. Postgres in particular is well-suited for full-text search. Django supports it out-of-the-box as well.

For the vast majority of your Django apps, you should, at the very least, start out with leveraging full-text search from Postgres before looking to a more powerful solution like ElasticSearch or Solr.

In this article, we’ll add basic and full-text search to a Django app with Postgres.


By the end of this article, you should be able to:

  1. Set up basic search functionality in a Django app with the Q object
  2. Add full-text search to a Django app
  3. Sort full-text search results by relevance using stemming, ranking, and weighting

#basic and full-text search with django and postgres #django #search lookup #postgres #full-text search #postgres full text search

Ananya Gupta


Main Pros and Cons of Django As A Web Framework for Python Developers

Django depicts itself as “the web system for fussbudgets with cutoff times”. It was intended to help Python engineers take applications from idea to consummation as fast as could be expected under the circumstances.

It permits fast turn of events on the off chance that you need to make a CRUD application with batteries included. With Django, you won’t need to rehash an already solved problem. It just works and lets you center around your business rationale and making something clients can utilize.

Pros of Django

“Batteries included” theory

The standard behind batteries-included methods normal usefulness for building web applications accompanies the system, not as isolated libraries.

Django incorporates much usefulness you can use to deal with normal web advancement undertakings. Here are some significant level functionalities that Django gives you, which else you need to stay together if you somehow happened to utilize a small scale structure:


Database relocations

Client validation

Administrator board


Normalized structure

Django as a system proposes the right structure of an undertaking. That structure helps designers in making sense of how and where to execute any new component.

With a generally acknowledged venture structure that is like numerous tasks, it is a lot simpler to discover online good arrangements or approach the network for help. There are numerous energetic Python designers who will assist you with comprehending any issue you may experience.

Django applications

Django applications (or applications for short) permit designers to separate a task into numerous applications. An application is whatever is introduced by putting in settings.INSTALLED_APPS. This makes it simpler for engineers to add usefulness to the web application by coordinating outer Django applications into the venture.

There are many reusable modules and applications to accelerate your turn of events learn through Online Django Class and Check the Django website.

Secure of course

Django gives great security assurance out of the crate and incorporates avoidance components for basic assaults like SQL Injection (XSS) and Cross-site Request Forgery (CSRF). You can discover more subtleties in the official security diagram control.

REST structure for building APIs

Django REST Framework, commonly condensed “DRF”, is a Python library for building APIs. It has secluded and adaptable engineering that functions admirably for both straightforward and complex web APIs.

DRF gives a lot of verification and authorization strategies out of the case. It is an adaptable, full-included library with measured and adjustable engineering. It accompanies nonexclusive classes for CRUD tasks and an implicit API program for testing API endpoints.

GraphQL structure for building APIs

Huge REST APIs regularly require a lot of solicitations to various endpoints to recover every single required datum. GraphQL it’s a question language that permits us to share related information in a lot simpler design. For a prologue to GraphQL and an outline of its ideas, if it’s not too much trouble allude to the authority GraphQL documentation.

Graphene-Django gives reflections that make it simple to add GraphQL usefulness to your Django venture. Ordinary Django models, structures, validation, consent arrangements, and different functionalities can be reused to manufacture GraphQL blueprint. It additionally gives an implicit API program for testing API endpoints.

Cons of Django

Django ORM

Django ORM, made before SQLAlchemy existed, is currently much sub-par compared to SQLAlchemy. It depends on the Active Record design which is more regrettable than the Unit of Work design embraced by SQLAlchemy. This implies, in Django, models can “spare” themselves and exchanges are off as a matter of course, they are a bit of hindsight. Peruse more in Why I kind of aversion Django.

Django advances course popularity increses day by day:

Django is huge and is viewed as strong bit of programming. This permits the network to create several reusable modules and applications yet has additionally restricted the speed of advancement of the Django. On head of that Django needs to keep up in reverse similarity, so it advances gradually.

Rundown - Should I use Django as a Python designer?

While Django ORM isn’t as adaptable as SQLAlchemy and the enormous environment of reusable modules and applications hinders structure advancement - plainly Django ought to be the best option web system for Python engineers.

Elective, light systems, similar to Flask, while offering a retreat from Django huge biological system and designs, in the long haul can require substantially more additional libraries and usefulness, in the end making many experienced Python engineers winding up wishing they’d began with Django.

Django undertaking’s security and network have become enormously over the previous decade since the system’s creation. Official documentation and instructional exercises are probably the best anyplace in programming advancement. With each delivery, Django keeps on including huge new usefulness.

#django online training #django online course #online django course #django course #django training #django certification course