Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Meta Class - Apply Ordering to user's model field

I am new to Django 1.9, I have an models.py :

class MyProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True)
    ContactNumber = models.CharField(max_length=100)

    class Meta:
        ordering = ('date_joined',)

Here I want to order table using date_joined which is field of User model.

When I am trying to run python manage.py makemigrations it gives me error as follows:

SystemCheckError: System check identified some issues:

ERRORS:
projectmanagement.UniservedTeam: (models.E015) 'ordering' refers to the non-existent field 'date_joined'.

How do i achieve this?

like image 899
Piyush S. Wanare Avatar asked May 16 '17 13:05

Piyush S. Wanare


People also ask

What is ordering in Meta class?

Ordering is basically used to change the order of your model fields.

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What is ordering in Django model?

Django order by lets you specify how your query results should be ordered. Here's an example where we will order by the author's name: class Author(models.Model): name = models.CharField() Author.objects.order_by("name")

Can we inherit models in Django?

Model Inheritance in Django works almost identically to the way normal class inheritance works in python. In this article we will revolve around how to create abstract base class in Django Models. Abstract Base Class are useful when you want to put some common information into a number of other models.


1 Answers

To set ordering on generic api views:

http://www.django-rest-framework.org/api-guide/filtering/#orderingfilter

use: ordering = ('user__date_joined', )

EDIT:

you can specify ordering on meta class like this:

class Meta:
    ordering = ('user__date_joined', )
like image 184
zaphod100.10 Avatar answered Sep 18 '22 19:09

zaphod100.10