问题
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