Emile
Emile

Reputation: 3484

Django: Filter foreignkey objects by default on model

I have 3 models what create a data hierarchy: Brand, Family, Car. In displaying the DetailView for the Brand, I have a table with a Brand's families (foreignkey) and in that table, I then have a property for num_cars to display the number of cars with a foreignkey back to that family.

Example:

Brand:Ford

Families:
Taurus 150
F150 100 
F250 0

This is displayed in my template as:

{% for family in brand.families.all %}
     {{ family }} {{ family.num_cars }}
{% endfor %}

Is there a way to filter the families by the number of cars so I don't see results where there are 0 cars? I can do this in the template with:

{% for family in brand.families.all %}
{% if family.num_cars > 0 %}
     {{ family }} {{ family.num_cars }}
{% endif %}
{% endfor %}

However that doesn't seem like the ideal solution. I'd like to have this in my models (if possible). Any ideas?

Upvotes: 0

Views: 428

Answers (2)

matyas
matyas

Reputation: 2796

You can achieve this kind of behavour with custom managers in Django. https://docs.djangoproject.com/en/1.10/topics/db/managers/ for example

class FamilyWithCarManager(models.Manager):
    def get_query_set(self):
       return super(FamilyWithCarManager, self).get_query_set().filter(num_cars__gte=0)

and then in your Family model:

class Family(models.Model):
    name = models.CharField(max_length=50)
    with_cars = FamilyWithCarManager()

then you should be able to write a query like this:

Family.with_cars.all()

Upvotes: 1

Bipul Jain
Bipul Jain

Reputation: 4643

You can add a method get_families to your model Brand

class Brand(models.Model):
    title = models.CharField()

    def get_families(self):
        return self.families.filter(num_cars__gt = 0)

And then do something like this in your views.

{% for family in brand.get_families %}
     {{ family }} {{ family.num_cars }}
{% endfor %}

Upvotes: 0

Related Questions