K
K
kieko2021-06-23 15:57:46
Django
kieko, 2021-06-23 15:57:46

How to create m2m dependencies?

How to do when creating an instance Studentin the database, a relationship will be created between the instance Studentand a number of model instances Course:
-Each model instance created Studentmust have a default relationship with some instances Course
-User cannot manually visit other parts of the site to add a new relationship between Studentand Course.

models.py

class Student(models.Model):
    name = models.CharField(max_length=249)

    def __str__(self):
        return f'{self.name}'

    def get_absolute_url(self):
        return reverse('index')


class Course(models.Model):
    name = models.CharField(max_length=249)
    student = models.ManyToManyField(Student, through='Connect')

    def __str__(self):
        return f'{self.name}'

class Connect(models.Model):
    student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True)
    course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True)


views.py:
class CreateStudent(LoginRequiredMixin, CreateView):
    login_url = '/admin/'
    redirect_field_name = 'index'
    template_name = 'app/create_student.html'
    model = Student
    fields = ('name',)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2021-06-23
@dimonchik2013

what exactly is unclear to you?
https://docs.djangoproject.com/en/3.2/topics/db/ex...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question