简体   繁体   中英

Django models ManyToMany relations mechanics

I need to create Profile model and Project model and don't really understand ManyToMany field mechanics.

Now I've got:

class Project(models.Model):
    title = models.CharField(max_length=20, unique=True)
    ...

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
    projects = models.ManyToManyField(Project, related_name='profiles')
    ...

Could I now call all profiles connected with project using project.profiles and how to add profiles field into Project admin form? I've tried to find some examples but not found any.

You can get all profiles from a Project doing something like that:

# Setup
project1 = Project.objects.get(title='first')
project2 = Project.objects.get(title='second')

profile = Profile.objects.create(user=user)
profile.projects.add(project2)

# Get all profiles from a project
project2.profiles.all()
>>> <QuerySet [<Profile: Profile object>]>

About forms, I'm not the best to answer that because I don't use, I prefer to use "raw" forms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM