I needed some help in model design. I wanted a model where a user can associate himself with numerous emails by submitting them from a form. And when the user wants to use the websites contact form, he can choose the email he wants a reply on. Will it be something like this :
class Email(models.Model):
author = models.ForeignKey(User)
email = models.EmailField()
class Contact(models.Model)
author = models.ForeignKey(User)
email = models.ForeignKey(Email)
2 Answers 2
Your example means each Contact can have a single email address, and each email address can belong to multiple contacts. This is the wrong way round, i.e. you should put the ForeignKey on the Email model.
This should let you store multiple email addresses for each user.
class Email(models.Model):
email = models.EmailField()
user = models.ForeignKey(User)
u = User.objects.get(pk=1)
u.email_set.all()
Comments
You want to add a user profile to your users.
from django.contrib import auth
class UserProfile(models.Model):
"""A user profile."""
user = models.OneToOneField(auth.models.User)
# ... put more fields here
def user_post_save(sender, instance, **kwargs):
"""Make sure that every new user gets a profile."""
profile, new = UserProfile.objects.get_or_create(user=instance)
models.signals.post_save.connect(user_post_save, sender=auth.models.User)
then you can access it with request.user.get_profile().
ForeignKey.