简体   繁体   中英

Filter two models django

I have two similar models:

class Boat(models.Model)
    
    name = models.CharField(max_length=140, help_text="Enter a Boat name")
    company = models.CharField(max_length=140)
    time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True)

    def __str__(self):

        return self.name
        
    class Meta:
        ordering = ['-time']

class Car(models.Model)
    
    name = models.CharField(max_length=140, help_text="Enter a Boat name")
    company = models.CharField(max_length=140)
    time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True)

    def __str__(self):

        return self.name
        
    class Meta:
        ordering = ['-time']

For example, there are 3 objects of the car model:

Name Created
Nissan Almera 02/2/2020
Renault Logan 01/9/2020
Mitsubishi L200 03/24/2021

and 1 one object of the boat model:

Name Created
wooden boat 01/01/2021

Is it possible to make a filter that would display the 3 most recently created objects? ie wooden boat, mitsubishi L200 and renault Logan

You can do it quite easily like this:

 Boat.objects.all().union(Car.objects.all(), all=True).order_by('time').limit(3).values("name")

Union is similar to the SQL UNIION operator

Yes. it is possible. Maybe there are many to do this. I'm using this solution for a long time. you can try this.

Example:

from itertools import chain
from operator import attrgetter

bots = Boat.objects.all()
cars = Car.objects.all()
bot_cars = sorted(chain(bots, cars), key=attrgetter('time'), reverse=True)[:3]

If these two models will always have same fields, its probably best to use a separate model Type to which your Object model has a ForeignKey relationship. You can also use choice fields if the types are not dynamic i,e only Boat and Car

Example TypeModel:

class Type(models.Model)
    name = models.CharField(max_length=50)

Example ObjectModel:

class Object(models.Model)
    type = models.ForeignKey(to=Type, on_delete=models.CASCADE)
    name = models.CharField(max_length=140)
    company = models.CharField(max_length=140)
    time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True)

    def __str__(self):

        return self.name
        
    class Meta:
        ordering = ['-time']

Now, you just need to query on one single model. I am suggesting this to avoid redundant model definitions
As for the help_text you can dynamically handle the help text depending on the chosen type in your template file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM