[Django]-How do you decide on creating a new model vs a field in django?

7👍

I generally find it useful to have separate models if the entries might be created independently. For example, if you might end up with a collection of addresses AND a collection of users, not all of which will be linked immediately, then I’d keep them separate.

However, if all addresses in your database will always and immediately be associated with a user, I’d simply add a new field to the model.

Note: some people will tell you that it’s wrong and evil to have nullable database columns, and that you should therefore have a separate model if any of your addresses will ever be None. I disagree; while there are often many great reasons to avoid nullable columns, in cases like this I don’t find the inconvenience of checking for a null address any more onerous than checking whether the one-to-one model entry exists.

4👍

Like Eli said, it’s a question of independence. For this particular example, I would make the address a field of UserProfile, but only if you expect to have one address per user. If each user might have multiple addresses (a home address and a vacation address, for example), then I would recommend setting up a model using ForeignKey, which models a Many-To-One relationship.

class UserProfile(models.Model):
    ...

class AddressModel(models.Model)
    user = models.ForeignKey(UserProfile)
    street_address = models.CharField(max_length=30)
    city = models.CharField(max_length=15)
    location = models.CharField(max_length=15) #"Home," "work," "vacation," etc.

Then many AddressModel objects can be created and associated with each UserProfile.

1👍

To answer your question, I’d say in general it’s probably better to separate out the address as mentioned by other users.

I think the more you learn about database normalization the easier this question is to answer.

This article, Using MySQL, Normalisation, should help you figure out the basics of the “forms” of normalization. BTW, even though it’s titled MySQL, it’s really very generic for relational databases.

While you don’t always need to go through all the normal-forms for all projects, learning about it really helps.

👤j_syk

Leave a comment