Django - Alternative to using NULLs? (for integer and FK fields).

47 views
Skip to first unread message

Victor Hooi

unread,
Nov 29, 2010, 8:28:13 PM11/29/10
to Django users
Hi,

I'm wondering what the community's stance on using NULL in Django is?

Say for example you have:

class Person(models.Model):
street_address = models.CharField(max_length=50, blank=True)
suburb = models.CharField(max_length=30)
postcode = models.IntegerField()
state = models.CharField(max_length=3)
email = models.EmailField()
mobile_phone_number = models.IntegerField(max_length=12)
home_phone_number = models.IntegerField(max_length=10,
null=True, blank=True)
work_phone_number = models.IntegerField(max_length=8,
null=True, blank=True)

spouse = models.ForeignKey('self', null=True, blank=True)
children = models.ManyToManyField('self', null=True,
blank=True)

For string fields like street_address, I can make these "blank=True",
and Django will store an empty string if the user leaves it blank.

However, for integer fields like home_phone_number and
work_phone_number, I've had to make these "null=True" for the case
where somebody doesn't supply them (i.e. they're meant to be optional,
mobile is required).

However, is there a better way of handling this case? (assuming I want
to keep these fields as integers).

What about in the case of optional foreign keys (spouse and children)
- is there a better way of handling these, without using NULLs?

Cheers,
Victor

Adam V.

unread,
Nov 29, 2010, 9:51:47 PM11/29/10
to Django users
A "phone number" is actually a character string, not an integer; so
use CharField for these as well.
For optional foreign keys, the standard (only?) database way to handle
these is indeed with a NULL value.

Lachlan Musicman

unread,
Nov 29, 2010, 11:11:26 PM11/29/10
to django...@googlegroups.com


Is it possible to know why you would want to keep them as integers?
Given that there are no mathematical functions that you would want to
apply to them....


> What about in the case of optional foreign keys (spouse and children)
> - is there a better way of handling these, without using NULLs?

As I understand it, foreign keys are kept in the db as follows:

1. table_Person
2. table_Person_children
3. table_Person_spouse

table 2 has three columns: id, Person, Children
table 3 has three columns: id, Person, Spouse

or something to that effect.

Therefore, if there is no Spouse or Child, there is no entry for
Person in tables 2 or 3.

> Cheers,
> Victor
>
> --
> You received this message because you are subscribed to the Google Groups "Django users" group.
> To post to this group, send email to django...@googlegroups.com.
> To unsubscribe from this group, send email to django-users...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
>
>

Victor Hooi

unread,
Nov 30, 2010, 12:26:52 AM11/30/10
to Django users
heya,

Phone Number - Yup, you're both right, I'll be using CharField now,
and model validation to make sure they're digits.

Spouse/Children:

With children, a M2M field, there's a link table, and if you don't
have a spouse, then there won't be any lines in that table. So no need
for NULLs there. I've just tested it with just blank=True, and no
null=True - seems to do what I want (optional children).

With ForeignKeyField though, I thought this was simply an FK field,
with the ID number of the object we're relating/pointing stored in
that field? Isn't that how it works in a normal DB? Why is there a
separate Person_spouse table?

Is there any way to make this optional without using NULLs, or should
I make it a m2m field? (I suppose in theory you can have multiple
spouses...well, not under my jurisdiction, I guess...lol).

Cheers,
Victor

On Nov 30, 3:11 pm, Lachlan Musicman <data...@gmail.com> wrote:

Mike Dewhirst

unread,
Nov 30, 2010, 1:02:21 AM11/30/10
to django...@googlegroups.com
On 30/11/2010 4:26pm, Victor Hooi wrote:
> heya,
>
> Phone Number - Yup, you're both right, I'll be using CharField now,
> and model validation to make sure they're digits.
>
> Spouse/Children:

Victor

I'm coming in late on this and don't have the context for your design
but I think there might be a better (perhaps more flexible) way to
handle spouses and children without worrying about NULLs.

I really like a single table for everyone. After all spouses and
children are persons too. You can use a separate table to hold named
many-to-many relationships between the person table and itself.

If the relationship is "Spouse" then that relationship speaks for
itself. Children can simultaneously have relationships with "Father",
"Mother", "Step-mother" etc. Other persons can have "Ex-spouse"
relationships when divorced etc.

If you can find any person then you can navigate through all the
relationships to find all connected persons.

Finally, if someone has multiple spouses then they probably need
counselling but at least you can represent it with multiple relationship
records :)

Mike

Victor Hooi

unread,
Nov 30, 2010, 1:10:41 AM11/30/10
to Django users
Mike,

Hmm, I'm currently using a recursive ('self') Many2Many and ForeignKey
for Children and Spouse, respectively (see source in the first post).

Is that what you meant?

Or perhaps I'm not quite getting what you mean - any chance you could
paste a models.py example so I can make sure I'm on the same page?

Cheers,
Victor

Mike Dewhirst

unread,
Nov 30, 2010, 1:33:24 AM11/30/10
to django...@googlegroups.com
On 30/11/2010 5:10pm, Victor Hooi wrote:
> Mike,
>
> Hmm, I'm currently using a recursive ('self') Many2Many and ForeignKey
> for Children and Spouse, respectively (see source in the first post).
>
> Is that what you meant?
>
> Or perhaps I'm not quite getting what you mean - any chance you could
> paste a models.py example so I can make sure I'm on the same page?

Victor

I'm keeping track of companies, divisions and people with their
relationships. For example, divisions can be traded between companies
and people consult to companies or own trading entities. I can also keep
track of pretty much any relationship of interest.

Hope this helps ...

class Entity(models.Model):
"""
Entities can be corporations or humans. entity_type indicates
which.
"""
entity_type = models.CharField(max_length=MEDIUM, blank=False,
choices=ENTITY_TYPES,
default=ENTITY_TYPES[0][0])
entity_name = models.CharField(max_length=LARGE, blank=False)
entity_title = models.CharField(max_length=SMALL, blank=True)
other_name = models.CharField(max_length=LARGE, blank=True)

slug = models.SlugField(max_length=VLARGE)

updated_by = models.ForeignKey(User, blank=True, null=True)
updated_date = models.DateTimeField(blank=True)
address = models.ForeignKey(Address, blank=True, null=True)

created = models.DateTimeField(auto_now_add=True)
saved = models.DateTimeField(auto_now=True)
saved_by = models.ForeignKey(User, blank=True, null=True,
related_name='entity_saved_by')
class Meta:
verbose_name_plural = 'entities'

def __unicode__(self):
ename = u' '.join(self.entity_title,
self.other_name,
self.entity_name)
return u'%s: %s (%s)' % (self.pk,
ename.strip(),
self.entity_type)


class Relationship(models.Model):
entity = models.ForeignKey(Entity, null=False,
related_name='rel_entity')
xref = models.ForeignKey(Entity, null=False,
related_name='xref_entity')
relationship = models.CharField(max_length=MEDIUM, blank=False,
choices=RELATIONSHIPS,
default=RELATIONSHIPS[0][0])
comment = models.CharField(max_length=HUGE, blank=True)
start_date = models.DateTimeField(blank=True, null=True)
end_date = models.DateTimeField(blank=True, null=True)

created = models.DateTimeField(auto_now_add=True)
saved = models.DateTimeField(auto_now=True)
saved_by = models.ForeignKey(User, blank=True, null=True,
related_name='relationship_saved_by')

def __unicode__(self):
return u'%s: %s ' % (self.relationship, self.xref)


Mike

Todd Wilson

unread,
Nov 30, 2010, 1:53:49 AM11/30/10
to django...@googlegroups.com
Mike Dewhirst wrote, on 11/29/2010 10:33 PM:
> I'm keeping track of companies, divisions and people with their
> relationships. For example, divisions can be traded between companies
> and people consult to companies or own trading entities. I can also keep
> track of pretty much any relationship of interest.
>
> Hope this helps ...
>
> class Entity(models.Model):
> """
> Entities can be corporations or humans. entity_type indicates
> which.
> """
> entity_type = models.CharField(max_length=MEDIUM, blank=False,
> choices=ENTITY_TYPES,
> default=ENTITY_TYPES[0][0])

Although this is not directly related to the question that started this
thread, your example raises a question that I've had as I've read the
documentation. Instead of hard-coding the entity types here, you are
using a constant, presumably because you may want to introduce more
entity types later. But what are the trade-offs bewteen representing
types as CharFields with choices, as you are doing here, versus a
separate table of types to which this model has a foreign-key
relationship? I'm facing this decision in a number of different places
in a Django application I'm working on.

Thanks,

--Todd

Torsten Bronger

unread,
Nov 30, 2010, 3:23:38 AM11/30/10
to django...@googlegroups.com
Hall�chen!

Todd Wilson writes:

> [...]
>
> [...] Instead of hard-coding the entity types here, you are using


> a constant, presumably because you may want to introduce more
> entity types later. But what are the trade-offs bewteen
> representing types as CharFields with choices, as you are doing
> here, versus a separate table of types to which this model has a
> foreign-key relationship?

I find choices much easier. Additionally, they behave more nicely
in ModelForms as they create a proper widget automatically. I use
FKs only if I want to attach additional information to the choices.

Tsch�,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jabber ID: torsten...@jabber.rwth-aachen.de
or http://bronger-jmp.appspot.com

Tom Evans

unread,
Nov 30, 2010, 5:29:05 AM11/30/10
to django...@googlegroups.com

You understand it incorrectly. A foreign key on fooapp.FooModelA to
fooapp.FooModelB would be modelled in the database as an
integer/foreign key field (depending on engine) called foomodelb_id on
table fooapp_foomodela.

>
> table 2 has three columns: id, Person, Children
> table 3 has three columns: id, Person, Spouse
>
> or something to that effect.
>
> Therefore, if there is no Spouse or Child, there is no entry for
> Person in tables 2 or 3.

You are describing an m2m relationship, not a foreign key.


Cheers

Tom

Jani Tiainen

unread,
Nov 30, 2010, 8:12:16 AM11/30/10
to django...@googlegroups.com

I try to answer this one since I spent good deal of my precious time to think
the exactly same thing while back.

I rarely use strings for actual values. It's just for preformance point of
view. It makes database easy to read but if you do constant searches by some
field you want to index it. And strings don't index well.

So it's also possible, and personally I opt for to use type-kind stuff as
integer field.

class MyMode(models.Model)
SOME_CHOICES = ((1, 'Choice 1'),
(2, 'Choice 2'))
my_field = models.IntegerField(choices=SOME_CHOICES, default=1)

to get visible representation of my_field you can do using built-in feature of
Django ORM:

instance_of_mymodel.get_my_field_display()

But when to use choices and when fk?

I use choices is when I have a relatively fixed set of options that basically
don't change ever. It's just that adding new stuff involves so much including
deployment to customer environments.

Foreign key I use when ever data is meant to be changed or edited by end user
or it contains much more data than simple textual value.

And as known relational databases are meant to handle um.. relational data.
And they do that very well. So it's not much of a problem to add models for
that kind of a data.

--

Jani Tiainen

Reply all
Reply to author
Forward
0 new messages