Don't call your Django model 'Return'
Let’s say you work for a company that handles customer returns. You would think naming your model Return
is a good idea. An example Return model is shown below:
class Return(models.Model):
store = models.OneToOneField(store)
order = models.OneToOneField(Order)
I quickly run dir(Store) and as expected, [..,'return', ..]
is in the output. I now have a reverse relationship ready to go! This is a very useful feature of Django.
Looks great right. Let me just show what it’s like dealing with this model in shell_plus
:
In[1]: print Store.objects.get(pk=1).return.pk
File "<ipython-input-41-e133fbd187e1>", line 1
print Store.objects.get(pk=1).return.pk
^
SyntaxError: invalid syntax
What? SyntaxError? Yes, SyntaxError. You cannot use the keyword return as an attribute or as a function name. The reverse relationship though is automatically generated and is perfectly valid.
How do you get around this with Django?
Quite simply, just use getattr(Store.objects.get(pk=1), 'return').pk
Now whether you should enforce relationships is another discussion for another overcast day.