Django Model Design

I needed help designing the model. I need a model in which a user can associate himself with numerous emails by sending them from a form. And when the user wants to use the contact form for websites, he can choose the email address to which he needs an answer. Would 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)
+3
source share
2 answers

In your example, each contact can have one email address, and each email address can belong to several contacts. This is the wrong way, i.e. You must put the ForeignKey in the email model.

.

class Email(models.Model):
    email = models.EmailField()
    user = models.ForeignKey(User)

u = User.objects.get(pk=1)
u.email_set.all()
+1

.

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)

request.user.get_profile().

0

Source: https://habr.com/ru/post/1761152/


All Articles