I want to create an expense tracking application, where each user can enter expenses and classify them into his own categories. Here is the model definition that I use:
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
user = models.ForeignKey(User, related_name="my_categories")
name = models.CharField(max_length=50)
class Expense(models.Model):
date = models.DateField()
amount = models.IntegerField()
description = models.TextField()
category = models.ForeignKey(Category)
user = models.ForeignKey开发者_JAVA技巧(User)
Each category will have to be associated with a user so that we can display each user his own categories to choose while entering the expense. For similar reasons, each expense record should be associated with a user. But in definition of Expense, we are having 2 references to the User models, one directly through 'user' field and another through the 'category' field which has a user reference.
I believe that multiple references like this is a bad thing. Is there a better way to model this? I understand that we can find out the user from the category reference, but it seems a roundabout way of doing it.
Although your db is not 100% normalized, in your case, I do not believe the second reference is redundant. Both 'an expense' and 'a category' are well defined entities, which belong to a user. If you will later want to change your foreign key to allow a null category or to a ManyToManyField, you will notice immediatly that both user fields are required. Lookups by user are also much easier for the db and developer when the column is there.
精彩评论