[Fixed]-Limit a Django ManyToMany by id

1👍

The Django Admin is meant as a database editor for developers, it is NOT meant for users.

With that in mind, the Cars list will always show all cars. To see which cars belong to a lot you need to go into the Parking list and edit one of the Parking objects. There you’ll see the options displayed as a multi-select list.

If you don’t like the multi-select list, you can override it using a ModelAdmin.

from django.contrib import admin
from myapps.models import Parking

class ParkingAdmin(admin.ModelAdmin):
     model = Parking
     filter_horizontal = ('options',)

This will create a control that looks like this:

filter_horizontal

However, if you need a more complete editable form for the related cars, you can use InlineModelAdmin.

from django.contrib import admin
from myapp.models import Car, Parking

class CarInline(admin.TabularInline):
    model = Car

class ParkingAdmin(admin.ModelAdmin):
    inlines = [CarInline,]

This will create a list at the bottom that looks like:

InlineModelAdmin

If you need more detailed views than this, you should create them yourself and not use the Admin. Once again, the Admin is for developers, NOT users.

👤Soviut

0👍

You can query for a particular parking lot and then traverse the options.

lot = Parking.objects.get(id=1)
cars = lot.options.all()

You can also query the Cars directly by filtering across the many to many relationship.

Car.objects.filter(parking__id=1)

In either case, Django will do the join for you in the background. If you want to see how Django is building the query, you can take any queryset and get the SQL using .query.

print Car.objects.filter(parking__id=1).query

To learn more about making queries and doing lookups across relationships read https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships

👤Soviut

0👍

Django offers the ForeignKey argument limit_choices_to. That is what you need, as the admin will respect your setting there.

Writing the correct code is left as en exercise. The link will guide you.

👤niklas

Leave a comment