To add a django ManyToMany relationship to data from an already existing model

Asked 2 years ago, Updated 2 years ago, 40 views

https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/

I'd like to ask you a question while looking at the Django manual.

After declaring the model, the manual creates an instance in the shell and stores the relationship data.

For data that is already stored, how can you link relational data?

I'm trying to follow the instructions on the shell, but the result keeps coming out as [] TT

django python migration

2022-09-21 17:20

1 Answers

Did you add models.manyToManyField on models.py and perform anytomakemigration and migrate? After that, the Admin will have a field like this, so you can add a movie to the actor.

And it can be done in Shell. You can work through the Shell command as shown below.

(1) Saving movies

>>> from movielibrary.models import Movie
>>> from movielibrary.models import Actress
>>> notting_hill = Movie.objects.filter(title='Notting hill')
>>> notting_hill
[<Movie: Notting hill>]
>>> notting_hill[0]
<Movie: Notting hill>
>>> Julia = Actress.objects.filter(title='Julia Roberts')[0]
>>> Julia
<Actress: Julia Roberts>
>>> Julia.movies.add(notting_hill[0])

(2) Loading saved information (based on actors)

>>> Julia.movies.all()
[<Movie: Pretty woman>, <Movie: Notting hill>]

(3) Loading saved information (based on movies)

>>> notting_hill[0].actress_set.all()
[<Actress: Julia Roberts>]


2022-09-21 17:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.