When the related value in foreign table is missing for an optional Foreign Key, I can either:
Set it to
nullPoint it to an empty string
''in the foreign table
It appears to me that if you follow Django design practices, you end up with option 2 (see code below). Is there any obvious advantage or downside with either approach?
Django favors 2 somewhat by design/convention. The docs say that null and '' are 2 possible values of "no-data". Hence if you omit the optional field, the forms will validate correctly and supply an empty string to which your Foreign Key can point to.
However logically, it seems like a missing value should imply a null or missing Foreign Key (instead of a valid Foreign Key that points to an empty value).
Moreover, storing blank would be a gotcha if I simply list all albums or do a count. Each time I've to remember to avoid the empty string. On the contrary, a null foreign key would never have an entry in the album table.
Reference:
- Can a foreign key be NULL...
- Can foreign key be NULL
- Django docs on null vs blank
Optional detail with code:
#models.py
class Album(Model):
name = CharField(max_length=50, unique=True)
class Song(Model):
name = CharField(max_length=50)
album = ForeignKey(Album, null=True, blank=True)
#forms.py
class SongForm(Form):
name = CharField(max_length=50)
album = CharField(max_length=50, required=False)
If you have a song with no album name, the form returns {'name':'foo', 'album':''}. This creates an entry in Album table with a blank name. I can circumvent that in the view (see code below). But this seems like a hack since data validation should be done in forms.
if album:
Song.objects.create(name=form.cleaned_data['name'], album=form.cleaned_data['album'])
else:
Song.objects.create(name=form.cleaned_data['name'], album_id=None)