简体   繁体   中英

Django 1.10 order_by() FieldError

With the below classes, I would like to be able select all related data for all "Ship_Back" objects and sort them by the "Ring" first, and the "Ppack" second.

When trying to order my queryset based on what I think the documentation is saying, and other posts I've read from previous versions of Django, I'm getting a FieldError. I tried simplifying it to just sort on the "Ppack" related table, but that's not working either.

Models:

class Ring(models.Model):
    ring = models.IntegerField()

class Ppack(models.Model):
    ppack = models.IntegerField()
    ring = models.ForeignKey('Ring', on_delete=models.CASCADE)

class Ship_Back(models.Model):
    ring_name = models.CharField(max_length = 20)
    release = models.ForeignKey('Ppack', on_delete=models.CASCADE)

Views:

def index(request):
    ship_back = Ship_Back.objects.all().order_by('Ppack__ppack')

This yields the following error:

FieldError at / Cannot resolve keyword 'Ppack' into field. Choices are: id, release, release_id, ring_name

Use instead:

order_by('release__ppack')

You use the field name of the ForeignKey in the filter, not the name of the related model. Imagine you had 2 ForeignKey relations to the same model, how would you distinguish them?

Accordingly, for the order you describe, you can do:

order_by('release__ring__ring', 'release__ppack')

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