All topics

Django interview questions

18 questions with answers. 163 open jobs in India ask for Django.

  1. What is the difference between null=True and blank=True in Django?

    null=True sets NULL (versus NOT NULL) on the column in your DB. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the DB.

    blank determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True then the field will not be required, whereas if it's False the field cannot be blank.

    The combo of the two is so frequent because typically if you're going to allow a field to be blank in your form, you're going to also need your database to allow NULL values for that field. The exception is CharFields and TextFields, which in Django are never saved as NULL. Blank values are stored in the DB as an empty string ('').

    A few examples:

    models.DateTimeField(blank=True) # raises IntegrityError if blank
    models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
    

    Obviously, Those two options don't make logical sense to use (though there might be a use case for null=True, blank=False if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)

    models.CharField(blank=True) # No problem, blank is stored as ''
    models.CharField(null=True) # NULL allowed, but will never be set as NULL
    

    CHAR and TEXT types are never saved as NULL by Django, so null=True is unnecessary. However, you can manually set one of these fields to None to force set it as NULL. If you have a scenario where that might be necessary, you should still include null=True.

    From Stack Overflow: asked by user993563, answered by Chris Pratt (CC BY-SA 4.0)

  2. Is there a list of Pytz Timezones?

    You can list all the available timezones with pytz.all_timezones:

    In [40]: import pytz
    In [41]: pytz.all_timezones
    Out[42]: 
    ['Africa/Abidjan',
     'Africa/Accra',
     'Africa/Addis_Ababa',
     ...]
    

    There is also pytz.common_timezones:

    In [45]: len(pytz.common_timezones)
    Out[45]: 403
    In [46]: len(pytz.all_timezones)
    Out[46]: 563
    

    From Stack Overflow: asked by ipegasus, answered by unutbu (CC BY-SA 3.0)

  3. What is a "slug" in Django?

    A "slug" is a way of generating a valid URL, generally using data already obtained. For instance, a slug uses the title of an article to generate a URL. I advise to generate the slug by means of a function, given the title (or another piece of data), rather than setting it manually.

    An example:

    <title> The 46 Year Old Virgin </title>
    <content> A silly comedy movie </content>
    <slug> the-46-year-old-virgin </slug>
    

    Now let's pretend that we have a Django model such as:

    class Article(models.Model):
        title = models.CharField(max_length=100)
        content = models.TextField(max_length=1000)
        slug = models.SlugField(max_length=40)
    

    How would you reference this object with a URL and with a meaningful name? You could for instance use Article.id so the URL would look like this:

    www.example.com/article/23
    

    Or, you might want to reference the title like this:

    www.example.com/article/The 46 Year Old Virgin
    

    Since spaces aren't valid in URLs, they must be replaced by %20, which results in:

    www.example.com/article/The%2046%20Year%20Old%20Virgin
    

    Both attempts are not resulting in very meaningful, easy-to-read URL. This is better:

    www.example.com/article/the-46-year-old-virgin
    

    In this example, the-46-year-old-virgin is a slug: it is created from the title by down-casing all letters, and replacing spaces by hyphens -.

    Also see the URL of this very web page for another example.

    From Stack Overflow: asked by Jonas, answered by Josh Smeaton (CC BY-SA 4.0)

  4. What does on_delete do on Django models?

    This is the behaviour to adopt when the referenced object is deleted. It is not specific to Django; this is an SQL standard. Although Django has its own implementation on top of SQL. (1)

    There are seven possible actions to take when such event occurs:

    • CASCADE: When the referenced object is deleted, also delete the objects that have references to it (when you remove a blog post for instance, you might want to delete comments as well). SQL equivalent: CASCADE.
    • PROTECT: Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually. SQL equivalent: RESTRICT.
    • RESTRICT: (introduced in Django 3.1) Similar behavior as PROTECT that matches SQL's RESTRICT more accurately. (See django documentation example)
    • SET_NULL: Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user. SQL equivalent: SET NULL.
    • SET_DEFAULT: Set the default value. SQL equivalent: SET DEFAULT.
    • SET(...): Set a given value. This one is not part of the SQL standard and is entirely handled by Django.
    • DO_NOTHING: Probably a very bad idea since this would create integrity issues in your database (referencing an object that actually doesn't exist). SQL equivalent: NO ACTION. (2)

    Source: Django documentation

    See also the documentation of PostgreSQL for instance.

    In most cases, CASCADE is the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation. PROTECT and SET_NULL are often useful. Setting CASCADE where it should not, can potentially delete all of your database in cascade, by simply deleting a single user.

    Additional note to clarify cascade direction

    It's funny to notice that the direction of the CASCADE action is not clear to many people. Actually, it's funny to notice that only the CASCADE action is not clear. I understand the cascade behavior might be confusing, however you must think that it is the same direction as any other action. Thus, if you feel that CASCADE direction is not clear to you, it actually means that on_delete behavior is not clear to you.

    In your database, a foreign key is basically represented by an integer field which value is the primary key of the foreign object. Let's say you have an entry comment_A, which has a foreign key to an entry article_B. If you delete the entry comment_A, everything is fine. article_B used to live without comment_A and don't bother if it's deleted. However, if you delete article_B, then comment_A panics! It never lived without article_B and needs it, it's part of its attributes (article=article_B, but what is article_B???). This is where on_delete steps in, to determine how to resolve this integrity error, either by saying:

    Read the rest at the sourceFrom Stack Overflow: asked by All Іѕ Vаиітy, answered by Antoine Pinsard (CC BY-SA 4.0)

  5. What is related_name used for?

    The related_name attribute specifies the name of the reverse relation from the User model back to your model.

    If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set, for instance User.map_set.all().

    If you do specify, e.g. related_name=maps on the User model, User.map_set will still work, but the User.maps. syntax is obviously a bit cleaner and less clunky; so for example, if you had a user object current_user, you could use current_user.maps.all() to get all instances of your Map model that have a relation to current_user.

    The Django documentation has more details.

    To disable creating the backwards relationship entirely, set related_name to "+".

    From Stack Overflow: asked by zjm1126, answered by Wogan (CC BY-SA 4.0)

  6. What's the difference between select_related and prefetch_related in Django ORM?

    Your understanding is mostly correct:

    • select_related: when the object that you're going to be selecting is a single object, so OneToOneField or a ForeignKey

    • prefetch_related: when you're going to get a "set" of things, so ManyToManyFields as you stated or reverse ForeignKeys.

    Just to clarify what I mean by reverse ForeignKeys, here's an example:

    class ModelA(models.Model):
        pass
    class ModelB(models.Model):
        a = ForeignKey(ModelA)
    # Forward ForeignKey relationship
    ModelB.objects.select_related('a').all()
    # Reverse ForeignKey relationship
    ModelA.objects.prefetch_related('modelb_set').all() 
    

    The difference is that:

    • select_related does an SQL join and therefore gets the results back as part of the table from the SQL server
    • prefetch_related on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA in the above example)

    You may use prefetch_related for anything that you can use select_related for.

    The tradeoffs are that prefetch_related has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.

    Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related has the extra benefit that a single object is used to represent each object in the database. With select_related duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.

    From Stack Overflow: asked by NeoWang, answered by CrazyCasta (CC BY-SA 4.0)

  7. OneToOneField() vs ForeignKey() in Django

    Differences between OneToOneField(SomeModel) and ForeignKey(SomeModel, unique=True) as stated in The Definitive Guide to Django:

    OneToOneField

    A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True, but the "reverse" side of the relation will directly return a single object.

    In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet.

    Example

    For example, if we have the following two models (full model code below):

    1. Car model uses OneToOneField(Engine)
    2. Car2 model uses ForeignKey(Engine2, unique=True)

    From within python manage.py shell execute the following:

    OneToOneField Example

    >>> from testapp.models import Car, Engine
    >>> c = Car.objects.get(name='Audi')
    >>> e = Engine.objects.get(name='Diesel')
    >>> e.car
    <Car: Audi>
    

    ForeignKey with unique=True Example

    >>> from testapp.models import Car2, Engine2
    >>> c2 = Car2.objects.get(name='Mazda')
    >>> e2 = Engine2.objects.get(name='Wankel')
    >>> e2.car2_set.all()
    [<Car2: Mazda>]
    

    Model Code

    from django.db import models
    class Engine(models.Model):
        name = models.CharField(max_length=25)
        def __unicode__(self):
            return self.name
    class Car(models.Model):
        name = models.CharField(max_length=25)
        engine = models.OneToOneField(Engine)
        def __unicode__(self):
            return self.name
    class Engine2(models.Model):
        name = models.CharField(max_length=25)
        def __unicode__(self):
            return self.name
    class Car2(models.Model):
        name = models.CharField(max_length=25)
        engine = models.ForeignKey(Engine2, unique=True, on_delete=models.CASCADE)
        def __unicode__(self):
            return self.name
    

    From Stack Overflow: asked by redice, answered by Matthew Rankin (CC BY-SA 4.0)

  8. What's the best way to extend the User model in Django?

    The least painful and indeed Django-recommended way of doing this is through a OneToOneField(User) property.

    Extending the existing User model

    …

    If you wish to store information related to User, you can use a one-to-one relationship to a model containing the fields for additional information. This one-to-one model is often called a profile model, as it might store non-auth related information about a site user.

    That said, extending django.contrib.auth.models.User and supplanting it also works...

    Substituting a custom User model

    Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.

    [Ed: Two warnings and a notification follow, mentioning that this is pretty drastic.]

    I would definitely stay away from changing the actual User class in your Django source tree and/or copying and altering the auth module.

    From Stack Overflow: asked by Farinha, answered by Ryan Duffield (CC BY-SA 4.0)

  9. Django Model() vs Model.objects.create()

    https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects

    To create and save an object in a single step, use the create() method.

    From Stack Overflow: asked by 0leg, answered by madzohan (CC BY-SA 4.0)

  10. Can I access constants in settings.py from templates in Django?

    If it's a value you'd like to have for every request & template, using a context processor is more appropriate.

    Here's how:

    1. Make a context_processors.py file in your app directory. Let's say I want to have the ADMIN_PREFIX_VALUE value in every context:

      from django.conf import settings # import the settings file
      def admin_media(request):
          # return the value you want as a dictionnary. you may add multiple values in there.
          return {'ADMIN_MEDIA_URL': settings.ADMIN_MEDIA_PREFIX}
      
    2. add your context processor to your settings.py file:

      TEMPLATES = [{
          # whatever comes before
          'OPTIONS': {
              'context_processors': [
                  # whatever comes before
                  "your_app.context_processors.admin_media",
              ],
          }
      }]
      
    3. Use RequestContext in your view to add your context processors in your template. The render shortcut does this automatically:

      from django.shortcuts import render
      def my_view(request):
          return render(request, "index.html")
      
    4. and finally, in your template:

      ...
      <a href="{{ ADMIN_MEDIA_URL }}">path to admin media</a>
      ...
      

    From Stack Overflow: asked by Paul Wicks, answered by bchhun (CC BY-SA 3.0)

  11. Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

    As another option, you can do lookups like:

    #models.py
    class UserAdmin(admin.ModelAdmin):
        list_display = (..., 'get_author')
        
        def get_author(self, obj):
            return obj.book.author
        get_author.short_description = 'Author'
        get_author.admin_order_field = 'book__author'
    

    For Django 3.2 or higher, please refer to this answer

    From Stack Overflow: asked by Huuuze, answered by imjoevasquez (CC BY-SA 4.0)

  12. Is it bad to have my virtualenv directory inside my git repository?

    I use pip freeze to get the packages I need into a requirements.txt file and add that to my repository. I tried to think of a way of why you would want to store the entire virtualenv, but I could not.

    From Stack Overflow: asked by Lyle Pratt, answered by RyanBrady (CC BY-SA 4.0)

  13. What's the difference between CharField and TextField in Django?

    It's a difference between RDBMS's varchar (or similar) — those are usually specified with a maximum length, and might be more efficient in terms of performance or storage — and text (or similar) types — those are usually limited only by hardcoded implementation limits (not a DB schema).

    PostgreSQL 9, specifically, states that "There is no performance difference among these three types", but AFAIK there are some differences in e.g. MySQL, so this is something to keep in mind.

    A good rule of thumb is that you use CharField when you need to limit the maximum length, TextField otherwise.

    This is not really Django-specific, also.

    From Stack Overflow: asked by Jonathan Gleason, answered by Cat Plus Plus (CC BY-SA 3.0)

  14. When saving a Django model, how can you check if a field has changed?

    Essentially, you want to override the __init__ method of models.Model so that you keep a copy of the original value. This makes it so that you don't have to do another DB lookup (which is always a good thing).

        class Person(models.Model):
            name = models.CharField()
            __original_name = None
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.__original_name = self.name
            def save(self, force_insert=False, force_update=False, *args, **kwargs):
                if self.name != self.__original_name:
                    # name changed - do something here
                super().save(force_insert, force_update, *args, **kwargs)
                self.__original_name = self.name
    

    From Stack Overflow: asked by Paul Tarjan, answered by Josh (CC BY-SA 4.0)

  15. Has Django served an excess of 100k daily visits?
    1. "What are the largest sites built on Django today?"

      There isn't any single place that collects information about traffic on Django built sites, so I'll have to take a stab at it using data from various locations. First, we have a list of Django sites on the front page of the main Django project page and then a list of Django built sites at djangosites.org. Going through the lists and picking some that I know have decent traffic we see:

    2. "Can Django deal with 100,000 users daily, each visiting the site for a couple of hours?"

      Yes, see above.

    3. "Could a site like Stack Overflow run on Django?"

      My gut feeling is yes but, as others answered and Mike Malone mentions in his presentation, database design is critical. Strong proof might also be found at www.cnprog.com if we can find any reliable traffic stats. Anyway, it's not just something that will happen by throwing together a bunch of Django models :)

    Read the rest at the sourceFrom Stack Overflow: asked by Roee Adler, answered by Van Gale (CC BY-SA 3.0)

  16. How do I do a not equal in Django queryset filtering?

    You can use Q objects for this. They can be negated with the ~ operator and combined much like normal Python expressions:

    from myapp.models import Entry
    from django.db.models import Q
    Entry.objects.filter(~Q(id=3))
    

    will return all entries except the one(s) with 3 as their ID:

    [<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
    

    From Stack Overflow: asked by MikeN, answered by Dave Vogt (CC BY-SA 4.0)

  17. How can I temporarily disable a foreign key constraint in MySQL?

    Try DISABLE KEYS or

    SET FOREIGN_KEY_CHECKS=0;
    

    Make sure to

    SET FOREIGN_KEY_CHECKS=1;
    

    after.

    From Stack Overflow: asked by jul, answered by Andrew Campbell (CC BY-SA 4.0)

  18. How to combine multiple QuerySets in Django?

    Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won't add further cost.

    from itertools import chain
    result_list = list(chain(page_list, article_list, post_list))
    

    Using itertools.chain is faster than looping each list and appending elements one by one, since itertools is implemented in C. It also consumes less memory than converting each queryset into a list before concatenating.

    Now it's possible to sort the resulting list e.g. by date (as requested in hasen j's comment to another answer). The sorted() function conveniently accepts a generator and returns a list:

    from operator import attrgetter
    result_list = sorted(
        chain(page_list, article_list, post_list),
        key=attrgetter('date_created')
    )
    

    You can reverse the sort order:

    result_list = sorted(
        chain(page_list, article_list, post_list),
        key=attrgetter('date_created'),
        reverse=True,
    )
    

    attrgetter is equivalet to the following lambda (this was the way it had to be done before Python 2.4):

    result_list = sorted(
        chain(page_list, article_list, post_list),
        key=lambda instance: instance.date_created,
    )
    

    From Stack Overflow: asked by espenhogbakk, answered by akaihola (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.