Home > Enterprise >  How to display value on fields based on queryset?
How to display value on fields based on queryset?

Time:04-28

i have a case like this : Models

class Car(models.Model):
     description = models.CharField(max_length=200)
     is_available = models.BooleanField(default=False)

class Rental(models.Model):
    car = models.ManyToManyField(Car)

My question is, how to display Car on Rental models with is_available = True. On django admin ? Thank you

CodePudding user response:

You can override get_queryset method of the django admin class.

Generic Syntax for that->

class MyModelAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(author=request.user)

In your case this would be -:

class RentalAdmin(admin.ModelAdmin):
    def get_queryset(self,request):
        qs = super().get_queryset(request)
        return qs.filter(car__is_available=True)

You can Refer to the docs here

For Inline your code should be -:

class CarInline(admin.StackedInline):
    model=Rental.car.through
    #model=Car
    def get_queryset(self,request):
        qs = super().get_queryset(request)
        return qs.filter(is_available=True)

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

CodePudding user response:

you can try django inline model admin

  • Related