开发者

How do you decide on creating a new model vs a field in django?

I'm creating a user profile c开发者_开发问答lass for my new django website, and I am trying to decide how to represent a user's physical address in my models.

Is it better practice to create a new subclass of model and reference it with a OneToOne key like

class UserProfile(models.Model):
    ...
   address = models.OneToOneField(AddressModel)
    ...
class AddressModel(models.Model)
    street_address = models.CharField(max_length=30)
    city = models.CharField(max_length=15)
     ....

or is it better to create a new address field like

class UserProfile(models.Model):
     ...
    address = AddressField(location_dict)
     ...
class AddressField(models.Field)
    # details go here
    ...


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜