[Fixed]-Get model objects in model of same model

1👍

This is a problem that would generally be solved at the form level.

The biggest roadblock right now is that there is no logic shown that shows what car models belong to what car brands. Django Smart Selects is often used to provide nested foreign key relations.

If that was properly set up and there was a CarModel model that was related to a brand, we could easily override the queryset provided to a modelform for brands. Take this example of a generic ModelForm; we will set the queryset in an overriden __init__ method.

from django import forms
from myapp.models import CarsForRent

class CarsForRentForm(forms.ModelForm):
    model = CarsForRent
    exclude = [] # or pass a list/tuple of field name string in a 'fields' parameter
    def __init__(self, *args, **kwargs):
        super(CarsForRentForm, self).__init__(*args, **kwargs)
        # access object through self.instance...
        self.fields['brand'].queryset = CarBrand.objects.filter(model__set__count__gt=0) # model__set represents the related_name parameter providen for CarModel's FK relation to CarBrand

Without seeing any way to tell what car models belong to which car brands, there is no way to perform an action like this. Feel free to add to the question if this logic is in place.

Leave a comment