Django interview questions
18 questions with answers. 163 open jobs in India ask for Django.
What is the difference between null=True and blank=True in Django?
null=TruesetsNULL(versusNOT NULL) on the column in your DB. Blank values for Django field types such asDateTimeFieldorForeignKeywill be stored asNULLin the DB.blankdetermines whether the field will be required in forms. This includes the admin and your custom forms. Ifblank=Truethen the field will not be required, whereas if it'sFalsethe 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
NULLvalues for that field. The exception isCharFields andTextFields, which in Django are never saved asNULL. 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 formObviously, Those two options don't make logical sense to use (though there might be a use case for
null=True, blank=Falseif 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 NULLCHARandTEXTtypes are never saved asNULLby Django, sonull=Trueis unnecessary. However, you can manually set one of these fields toNoneto force set it asNULL. If you have a scenario where that might be necessary, you should still includenull=True.From Stack Overflow: asked by user993563, answered by Chris Pratt (CC BY-SA 4.0)
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]: 563From Stack Overflow: asked by ipegasus, answered by unutbu (CC BY-SA 3.0)
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/23Or, you might want to reference the title like this:
www.example.com/article/The 46 Year Old VirginSince spaces aren't valid in URLs, they must be replaced by
%20, which results in:www.example.com/article/The%2046%20Year%20Old%20VirginBoth attempts are not resulting in very meaningful, easy-to-read URL. This is better:
www.example.com/article/the-46-year-old-virginIn this example,
the-46-year-old-virginis 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)
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 asPROTECTthat matches SQL'sRESTRICTmore 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,
CASCADEis the expected behaviour, but for every ForeignKey, you should always ask yourself what is the expected behaviour in this situation.PROTECTandSET_NULLare often useful. SettingCASCADEwhere 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
CASCADEaction is not clear to many people. Actually, it's funny to notice that only theCASCADEaction 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 thatCASCADEdirection is not clear to you, it actually means thaton_deletebehavior 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 whereon_deletesteps 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)
What is related_name used for?
The
related_nameattribute specifies the name of the reverse relation from theUsermodel 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 instanceUser.map_set.all().If you do specify, e.g.
related_name=mapson theUsermodel,User.map_setwill still work, but theUser.maps.syntax is obviously a bit cleaner and less clunky; so for example, if you had a user objectcurrent_user, you could usecurrent_user.maps.all()to get all instances of yourMapmodel that have a relation tocurrent_user.The Django documentation has more details.
To disable creating the backwards relationship entirely, set
related_nameto"+".From Stack Overflow: asked by zjm1126, answered by Wogan (CC BY-SA 4.0)
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, soOneToOneFieldor aForeignKeyprefetch_related: when you're going to get a "set" of things, soManyToManyFields as you stated or reverseForeignKeys.
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_relateddoes an SQL join and therefore gets the results back as part of the table from the SQL serverprefetch_relatedon the other hand executes another query and therefore reduces the redundant columns in the original object (ModelAin the above example)
You may use
prefetch_relatedfor anything that you can useselect_relatedfor.The tradeoffs are that
prefetch_relatedhas 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_relatedhas the extra benefit that a single object is used to represent each object in the database. Withselect_relatedduplicate 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)
OneToOneField() vs ForeignKey() in Django
Differences between
OneToOneField(SomeModel)andForeignKey(SomeModel, unique=True)as stated in The Definitive Guide to Django:OneToOneField
A one-to-one relationship. Conceptually, this is similar to a
ForeignKeywithunique=True, but the "reverse" side of the relation will directly return a single object.In contrast to the
OneToOneField"reverse" relation, aForeignKey"reverse" relation returns aQuerySet.Example
For example, if we have the following two models (full model code below):
Carmodel usesOneToOneField(Engine)Car2model usesForeignKey(Engine2, unique=True)
From within
python manage.py shellexecute the following:OneToOneFieldExample>>> from testapp.models import Car, Engine >>> c = Car.objects.get(name='Audi') >>> e = Engine.objects.get(name='Diesel') >>> e.car <Car: Audi>ForeignKeywithunique=TrueExample>>> 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.nameFrom Stack Overflow: asked by redice, answered by Matthew Rankin (CC BY-SA 4.0)
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.Userand supplanting it also works...Substituting a custom User model
Some kinds of projects may have authentication requirements for which Django’s built-in
Usermodel 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)
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)
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:
Make a
context_processors.pyfile in your app directory. Let's say I want to have theADMIN_PREFIX_VALUEvalue 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}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", ], } }]Use
RequestContextin your view to add your context processors in your template. Therendershortcut does this automatically:from django.shortcuts import render def my_view(request): return render(request, "index.html")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)
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)
Is it bad to have my virtualenv directory inside my git repository?
I use
pip freezeto get the packages I need into arequirements.txtfile 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)
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 — andtext(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
CharFieldwhen you need to limit the maximum length,TextFieldotherwise.This is not really Django-specific, also.
From Stack Overflow: asked by Jonathan Gleason, answered by Cat Plus Plus (CC BY-SA 3.0)
When saving a Django model, how can you check if a field has changed?
Essentially, you want to override the
__init__method ofmodels.Modelso 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.nameFrom Stack Overflow: asked by Paul Tarjan, answered by Josh (CC BY-SA 4.0)
Has Django served an excess of 100k daily visits?
"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:
Instagram: What Powers Instagram: Hundreds of Instances, Dozens of Technologies.
Pinterest: Alexa rank 37 (21.4.2015) and 70 Million users in 2013
tabblo.com: 44k daily visits, see Ned Batchelder's posts Infrastructure for modern web sites.
chesspark.com: Alexa rank about 179k.
pownce.com (no longer active): alexa rank about 65k. Mike Malone of Pownce, in his EuroDjangoCon presentation on Scaling Django Web Apps says "hundreds of hits per second". This is a very good presentation on how to scale Django, and makes some good points including (current) shortcomings in Django scalability.
HP had a site built with Django 1.5: ePrint center. However, as for novemer/2015 the entire website was migrated and this link is just a redirect. This website was a world-wide service attending subscription to Instant Ink and related services HP offered (*).
"Can Django deal with 100,000 users daily, each visiting the site for a couple of hours?"
Yes, see above.
"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)
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
3as 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)
How can I temporarily disable a foreign key constraint in MySQL?
Try
DISABLE KEYSorSET 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)
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.chainis faster than looping each list and appending elements one by one, sinceitertoolsis 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, )attrgetteris equivalet to the followinglambda(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.
- Stack Overflowby its contributors, named on each answerCC BY-SA18 questions