简体   繁体   中英

Django - working with queryset

My models currently look like this:

class Dealer(models.Model):
    name = models.CharField(unique=True, max_length=255, default='')
    url = models.URLField()

    def __str__(self):
        return self.name


class Category(models.Model):
    name = models.CharField(unique=True, max_length=255, default='')

    def __str__(self):
        return self.name


class Car(models.Model):
    name = models.CharField(unique=False, max_length=255,default='')
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class Price(models.Model):
    car = models.ForeignKey(Car, default='')
    dealer = models.ForeignKey(Dealer, default='')
    price = models.DecimalField(max_digits=9, decimal_places=2)
    url = models.URLField(max_length=255)

    def __str__(self):
        return str(self.price)

What I want to be able to do is answer the following question (something that will ultimately become the context of my view): Show me a list of cars in a particular category that are available at different dealerships, with their prices. The query that I'm using for testing is this:

carprice = Price.objects.filter(car__category='1').values('car__name','price','dealer__name').order_by('car__name')

The resulting QuerySet looks something like this:

<QuerySet [{'car__name': 'Audi Model A', 'price': Decimal('32000.00'), 'dealer__name': 'Dealer A'}, {'car__name': 'Audi Model A', 'price': Decimal('35000.00'), 'dealer__name': 'Dealer B'}, {'car__name': 'Audi Model A', 'price': Decimal('35000.00'), 'dealer__name': 'Dealer C'}, '...(remaining elements truncated)...']>

Question 1: Can the query be modified so that the QuerySet does not repeat the car__name every time but instead groups prices and dealers by car__name? If someone could point me to a good tutorial/documentation on QuerySets, I would be really grateful. I've tried looking at Django's documentation and couldn't really find an answer to this question.

- Audi Model A
    - Dealer A 32000.00
    - Dealer B 35000.00
    - Dealer C 35000.00

Question 2: With the current query, how can the grouping be done in the view function to achieve the look above?

For anyone visiting this page looking for an answer, here's the best I could come up with:

Question 1 : Based on my review of Django documentation and the interaction I had with another Django developer, the answer is (probably) no.

Question 2 : The answer is: regroup template tag. Reference

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