Souvik Halder
Souvik Halder

Reputation: 11

many attributes in manyTomanyField does not have a attribute called .all()

I have created a model named Flight which is connected to another model named Passengers

flights = models.ManyToManyField(Flight, blank=True, related_name="passengers")

i tried to use Passengers = Flight.Passengers.all() it throws an error saying that

Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'ManyToManyDescriptor' object has no attribute 'all'

need help with it!

i want only the realted fields from flight and passengers into my html but it throw an error whenever i try to access using Flight.Passengers.all() and Flight.Passengers.get()

it can be bypass using Passengers.objects.all() but i don't need that otherwise there will be no relation between my databases!

Upvotes: 1

Views: 30

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477533

That makes perfect sense, the related_name works with a Flight object, not the Flight class, what would that even mean?

You thus fetch a Flight object:

my_flight = Flight.objects.get(pk=1)  # Flight object with pk=1

and then you get the passengers of the my_flight with:

my_flight.passengers.all()

It does not work with the Flight class, the only sensical response for that would be returning all Passengers that have at least one flight. You can do that with:

# Passengers linked to at least one Flight
Passenger.objects.filter(flights__isnull=False).distinct()

Upvotes: 0

Related Questions