Django - how to normalize database?

╄→гoц情女王★ 提交于 2019-12-25 06:07:01

问题


I keep asking people how I should organize my model, and they keep telling me to normalize the database.

Can someone show me an example of a normalized Django model?


回答1:


Normalisation is not a Django or even Python concept - it is a wider approach to designing a relational database schema such that you remove duplication and eliminate redundancy.

In django this means that rather than have one model, you might have multiple smaller models, which represent the relationship between database tables via ForeignKey and ManyToMany fields provided by the Model API.

So using an example contrived from the django docs, say we work for a newspaper company and we want to keep track of each reporter and the articles they publish. You might design a model like this first off

class Newspaper(models.Model):
    reporter = models.CharField(max_length=30)
    email = models.EmailField()
    headline = models.CharField(max_length=100)

If we populate this model, we are going to have redundancy as soon as a reporter publishes more than one article, as we will be duplicating email information, storing the same email address in multiple rows. This is a problem, as in the future if we want to update a reporters email address, we might a miss row and corrupt our data.

So we could start to improve on this and begin to normalise our model by defining two separate tables, which use a ForeignKey field to map the many-to-one relationship (aka that a reporter can publish many articles, but an article only has one reporter).

class Reporter(models.Model):
    name = models.CharField(max_length=30)
    email = models.EmailField()

class Article(models.Model):
    headline = models.CharField(max_length=100)
    reporter = models.ForeignKey(Reporter)

Now we won't be duplicating the reporters email address, as we can store this ONCE in the Reporter table, making it easier to update this value in the future.

Now this is a somewhat contrived answer, and I'm sure you could go further to improve this design, but hopefully it demonstrates the point. I really recommend you read the django docs which talk about the modeling of relationships and the various degrees of normalisation.



来源:https://stackoverflow.com/questions/23093370/django-how-to-normalize-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!