The program I’m making is to display information about a product from the database. The program works fine, the problem is that I want to order by last name and not the “owner”. For example. If the customer username is ewOI, which this is the “owner”, and his name is Robert and last name is Bosh, I want to order the queryset by the last name and not the owner.
Here is the views code:
class ExpView(ListView): context_object_name = 'product' queryset = Product.objects.filter(prod__isnull=True).order_by('owner') template_name = 'productrecords.html' paginate_by = 10
there are two models, the one in product, and the one in user The product models:
class Product(models.Model): owner = models.ForeignKey( User, on_delete=models.PROTECT, related_name='products' ) id_subscription = models.CharField(max_length=30, unique=True) amount = models.DecimalField(max_digits=11, decimal_places=2, null=True) interest_rate = models.DecimalField(max_digits=4, decimal_places=2) start_date = models.DateField(null=True)
And the user models:
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True) second_name = models.CharField(max_length=32, blank=True) last_name2 = models.CharField(max_length=32, blank=True) recovery_email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=16, unique=True, null=True)
Which for example if i go to the terminal and try to bring the query from the db:
But I want to order_by(‘last_name’) but that doesn’t work. How can I order it?
Thank you very much
Advertisement
Answer
did you try this?
queryset = Product.objects.filter(prod__isnull=True).order_by('owner__last_name2')
You can call a field from a foreign key by typing __.