The right way to add a record to many relationships in Django

Firstly, I plan to run my project in a google application, so I use djangoappengine , which, as far as I know, does not support the django type ManyToManyField. Because of this, I configured my models as follows:

from django.db import models
from django.contrib.auth.models import User

class Group(models.Model):
    name = models.CharField(max_length=200)

class UserGroup(models.Model):
    user = models.ForeignKey(User)
    group = models.ForeignKey(Group)

On the page, I have a form field where people can enter a group name. I want the results from this form field to create a UserGroup object for a combination of user groups, and if the group does not already exist, create a new Group object. At first, I started using this logic in the UserGroup class using a method add_group, but quickly realized that it really makes no sense to put this in a class UserGroup. What would be the right way to do this? I saw something about model managers. What is it for?

+3
source share
1 answer

From the Django docs :

A dispatcher is an interface through which database query operations are provided to Django models.

, .

Group, User ( ) UserGroup.

, Group Group(name='group name', user=some_user), User UserGroup User:

class Group(models.Model):
    name = models.CharField(max_length=200)

    def __init__(self, *args, **kwargs):
        # Remove user from the kwargs.
        # It is important that user is removed from the kwargs before calling
        # the super.__init__(). This is because the `user` kwarg is not expected.
        user = kwargs.pop('user', None)

        # call the normal init method
        super(Group, self).__init__(*args, **kwargs)

        # Create the UserGroup instance for the specified user
        if user is not None:
            # Maybe some other logic here ...
            UserGroup(user=user, group=self).save()

, User Group, UserGroup .

, UserGroup , , .

EDIT:

, :

...
def __init__(self, *args, **kwargs):
    ...
    self._user_group = UserGroup(user=user, group=self)

def save(self, *args, **kwargs):
    super(Group, self).save(*args, **kwargs)
    self._user_group.save()
+3
source

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


All Articles