Narasimha Ponnam
Narasimha Ponnam

Reputation: 55

Problem Related Many to many relationship in Django

I am creating a relationship between Username and User_edu, this is bidirectional code of model.py

from django.db import models 
class username(models.Model):
    name=models.CharField(max_length=100)
class user_edu(models.Model):
    qualification=models.CharField(max_length=100)
    clgname=models.CharField(max_length=100)
    marks=models.CharField(max_length=100)
    year_of_graduation=models.CharField(max_length=100)
    uname=models.ManyToManyField(username)

In views.py

viewue = user_edu.objects.all()
if request.method == 'POST':
    obj = username.objects.get(id=id)
    uq = user_edu.objects.get(id=request.POST['qualification'])
    uc = user_edu.objects.get(id=request.POST['clgname'])
    um = user_edu.objects.get(id=request.POST['marks'])
    uy = user_edu.objects.get(id=request.POST['year_of_graduation'])
    uq.uname.add(obj)
    uc.uname.add(obj)
    um.uname.add(obj)
    uy.uname.add(obj)
    uq.save()
    uc.save()
    um.save()
    uy.save()
    return render(request, 'data.html', {'user_edu_all': viewue})
else:
    obj = username.objects.get(id=id)
    return render(request, 'data.html', {'user_edu_all': viewue})

I am trying to do that the user will register the name first in one webpage and that they will give the details of the education in another page how to relate user and educationdetails

Upvotes: 0

Views: 41

Answers (1)

bruzza42
bruzza42

Reputation: 403

You need to use model relationships. Check out the documentation https://docs.djangoproject.com/en/3.0/topics/db/models/

And specifically Many-To-One (ForeignKey) relations. https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_one/

Upvotes: 1

Related Questions