How to access Model’s pk/id when you create an instance in Django

If you need to modify instance fields depending on the instance’s pk or id, hop on.

When you create an instance, before it is saved, you can’t have pk or id as it is not yet created.

    def save(self, *args, **kwargs):
        # == None
        # == None
        super().save(*args, **kwargs)
        # != None
        # != None        

If you have a property that somehow depends on the value of or and you want to have it saved on creating, you have two options.

Read More »

GenericView: Attributeerror ‘list’ object has no attribute ‘filter’ // 1-second guide 😮💢

So you are casually overriding get_queryset() in a, say, ListView, like this:

def get_queryset(self):
    entries = [x for x in Entry.objects.all() if x.publications]
    return entries

Because you need to sort the Entry table by a reverse M2M relation publications and then BAM!:

Attribute error 'list' object has no attribute 'filter'

Without a trace of the line you made a mistake in…

Read More »