EzDevInfo.com

django-models interview questions

Top django-models frequently asked interview questions

What is a "slug" in Django?

When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used?

(I have read its definition in this glossary.)


Source: (StackOverflow)

django orm, how to view (or log) the executed query?

Is there a way I can print the query the Django ORM is generating?

Say I execute the following statement: Model.objects.filter(name='test')

How do I get to see the generated SQL query?


Source: (StackOverflow)

Advertisements

Django database query: How to filter objects by date range?

I've got a field in one model like

class Sample(models.Model):
    date = fields.DateField(auto_now=False)

Now, I need to filter the objects by a data range, for example, all the objects that has date between 1 Jan 2011 to 31 Jan 2011?

Thanks for your help!


Source: (StackOverflow)

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

In Django model QuerySets, I see that there is a __gt and __lt for comparitive values, but is there a __ne/!=/<> (not equals?)

I want to filter out using a not equals:

Example:

Model:
    bool a;
    int x;

I want

results = Model.objects.exclude(a=true, x!=5)

The != is not correct syntax. I tried __ne, <>.

I ended up using:

results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5)

Source: (StackOverflow)

differentiate null=True, blank=True in django

When we add a database field in django we generally write models.CharField(max_length=100, null=True, blank=True). The same is done with ForeignKey, DecimalField etc. What is the basic difference in having

  1. null=True only
  2. blank=True only
  3. null=True, blank=True

in respect to different (CharField, ForeignKey, ManyToManyField, DateTimeField) fields. What are the advantages/disadvantages of using 1/2/3?


Source: (StackOverflow)

How to define two fields "unique" as couple

Is there a way to define a couple of fields as unique in Django?

I have a table of volumes (of journals) and I don't want more then one volume number for the same journal.

class Volume(models.Model):
    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

I tried to put unique = True as attribute in the fields journal_id and volume_number but it doesn't work.


Source: (StackOverflow)

How do you serialize a model instance in Django?

There is a lot of documentation on how to serialize a Model QuerySet but how do you just serialize to json the fields of a Model Instance?


Source: (StackOverflow)

Filtering for empty or NULL names in a queryset

I have first_name, last_name & alias (optional) which I need to search for. So, I need a query to give me all the names that have an alias set.

Only if I could do:

Name.objects.filter(alias!="")

So, what is the equivalent to the above?


Source: (StackOverflow)

Django: Why do some model fields clash with each other?

I want to create an object that contains 2 links to Users. For example:

class GameClaim(models.Model):
    target = models.ForeignKey(User)
    claimer = models.ForeignKey(User)
    isAccepted = models.BooleanField()

but I am getting the following errors when running the server:

  • Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.

  • Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.

Can you please explain why I am getting the errors and how to fix them?


Source: (StackOverflow)

Django: When saving, how can you check if a field has changed?

In my model I have :

class Alias(MyBaseModel):
    remote_image = models.URLField(max_length=500, null=True, help_text="A URL that is downloaded and cached for the image. Only
 used when the alias is made")
    image = models.ImageField(upload_to='alias', default='alias-default.png', help_text="An image representing the alias")


    def save(self, *args, **kw):
        if (not self.image or self.image.name == 'alias-default.png') and self.remote_image :
            try :
                data = utils.fetch(self.remote_image)
                image = StringIO.StringIO(data)
                image = Image.open(image)
                buf = StringIO.StringIO()
                image.save(buf, format='PNG')
                self.image.save(hashlib.md5(self.string_id).hexdigest() + ".png", ContentFile(buf.getvalue()))
            except IOError :
                pass

Which works great for the first time the remote_image changes.

How can I fetch a new image when someone has modified the remote_image on the alias? And secondly, is there a better way to cache a remote image?


Source: (StackOverflow)

Programmatically saving image to Django ImageField

Ok, I've tried about near everything and I cannot get this to work.

  • I have a Django model with an ImageField on it
  • I have code that downloads an image via HTTP (tested and works)
  • The image is saved directly into the 'upload_to' folder (the upload_to being the one that is set on the ImageField)
  • All I need to do is associate the already existing image file path with the ImageField

I've written this code about 6 different ways.

The problem I'm running into is all of the code that I'm writing results in the following behavior: (1) Django will make a 2nd file, (2) rename the new file, adding an _ to the end of the file name, then (3) not transfer any of the data over leaving it basically an empty re-named file. What's left in the 'upload_to' path is 2 files, one that is the actual image, and one that is the name of the image,but is empty, and of course the ImageField path is set to the empty file that Django try to create.

In case that was unclear, I'll try to illustrate:

## Image generation code runs.... 
/Upload
     generated_image.jpg     4kb

## Attempt to set the ImageField path...
/Upload
     generated_image.jpg     4kb
     generated_image_.jpg    0kb

ImageField.Path = /Upload/generated_image_.jpg

How can I do this without having Django try to re-store the file? What I'd really like is something to this effect...

model.ImageField.path = generated_image_path

...but of course that doesn't work.

And yes I've gone through the other questions here like this one as well as the django doc on File

UPDATE After further testing, it only does this behavior when running under Apache on Windows Server. While running under the 'runserver' on XP it does not execute this behavior.

I am stumped.

Here is the code which runs successfully on XP...

f = open(thumb_path, 'r')
model.thumbnail = File(f)
model.save()

Source: (StackOverflow)

Django auto_now and auto_now_add

For Django 1.1.

I have this in my models.py:

class User(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

When updating a row I get:

[Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base.py:84: Warning: Column 'created' cannot be null
[Sun Nov 15 02:18:12 2009] [error]   return self.cursor.execute(query, args)

The relevant part of my database is:

  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,

Is this cause for concern?

Side question: in my admin tool, those two fields aren't showing up. Is that expected?


Source: (StackOverflow)

Django FileField with upload_to determined at runtime

I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks:

class Content(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey(User)
    file = models.FileField(upload_to='.')

So what I want is instead of '.' as the upload_to, have it be the user's name.

I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost.

Thanks for the help!


Source: (StackOverflow)

How to pull a random record using Django's ORM?

I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one.

I'm using Django 1.0.2.

While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this:

number_of_records = models.Painting.objects.count()
random_index = int(random.random()*number_of_records)+1
random_paint = models.Painting.get(pk = random_index)

It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things.

Any other options how I can do it, preferably somehow inside the model abstraction?


Source: (StackOverflow)

Django dynamic model fields

I'm working on a multi-tenanted application in which some users can define their own data fields (via the admin) to collect additional data in forms and report on the data. The latter bit makes JSONField not a great option, so instead I have the following solution:

class CustomDataField(models.Model):
    """
    Abstract specification for arbitrary data fields.
    Not used for holding data itself, but metadata about the fields.
    """
    site = models.ForeignKey(Site, default=settings.SITE_ID)
    name = models.CharField(max_length=64)

    class Meta:
        abstract = True

class CustomDataValue(models.Model):
    """
    Abstract specification for arbitrary data.
    """
    value = models.CharField(max_length=1024)

    class Meta:
        abstract = True

Note how CustomDataField has a ForeignKey to Site - each Site will have a different set of custom data fields, but use the same database. Then the various concrete data fields can be defined as:

class UserCustomDataField(CustomDataField):
    pass

class UserCustomDataValue(CustomDataValue):
    custom_field = models.ForeignKey(UserCustomDataField)
    user = models.ForeignKey(User, related_name='custom_data')

    class Meta:
        unique_together=(('user','custom_field'),)

This leads to the following use:

custom_field = UserCustomDataField.objects.create(name='zodiac', site=my_site) #probably created in the admin
user = User.objects.create(username='foo')
user_sign = UserCustomDataValue(custom_field=custom_field, user=user, data='Libra')
user.custom_data.add(user_sign) #actually, what does this even do?

But this feels very clunky, particularly with the need to manually create the related data and associate it with the concrete model. Is there a better approach?

Options that have been pre-emptively discarded:

  • Custom SQL to modify tables on-the-fly. Partly because this won't scale and partly because it's too much of a hack.
  • Schema-less solutions like NoSQL. I have nothing against them, but they're still not a good fit. Ultimately this data is typed, and the possibility exists of using a third-party reporting application.
  • JSONField, as listed above, as it's not going to work well with queries.

Source: (StackOverflow)