Answer the question
In order to leave comments, you need to log in
How to create m2m dependencies?
How to do when creating an instance Student
in the database, a relationship will be created between the instance Student
and a number of model instances Course
:
-Each model instance created Student
must have a default relationship with some instances Course
-User cannot manually visit other parts of the site to add a new relationship between Student
and 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)
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question