2

I want to create a method semi to values method in Django QuerySet.

The values method problems are:

  1. Miss order of fields in querySet if I make myquery = MyModel.objects.values('field1','field2','field3') when I print querSet it give me [{'field2':'data','field1':'data','field3':'data'},...]. so this miss order will cause a problem at Union of queryset.
  2. if the field is choices at model then values(...) will give me the key of dictionary instead of its value.
  • I want to create my custom values method using django Manager

    
    class MyModelManager(models.Manager):
        def values(self, *fields):
            # I want to get model belong to this manger
            # then I want to check the fields if its in models (we have fields came from annotate)
            # after that I want to exclude to the fields that has choices 
            # next I want to call the super values method and passed to it the values that does not have choices
            # finally I want to reorder query according to passed fields
    
    class MyModel(models.model):
        # An example model
        objects = MyModelManager()
    
    
AlASAD WAIL
  • 775
  • 4
  • 18
  • you can pass `named=True` and use `values_list ` instead of `values` with `queryset`. It will return `namedtuple` which may satisfy your use case. Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list – Abhyudai Jan 23 '21 at 07:03
  • 1
    Why would the order of the keys in the returned dictionaries cause a problem with a `Union`? – Iain Shelvington Jan 24 '21 at 06:28
  • Why not simply use the `get__display` method Django makes for each field with choices? – Abdul Aziz Barkat Jan 24 '21 at 06:40
  • @lain **union** ,the union is apply if and only if all queryset have the same order. you can read the Union conditions here [https://docs.djangoproject.com/en/3.1/ref/models/querysets/#union – AlASAD WAIL Jan 24 '21 at 07:25
  • @AbdulAzizBarkat you are right, but I want to improve the performance instead of iteration around all queryset. – AlASAD WAIL Jan 24 '21 at 07:30
  • @AlASADWAIL Your problem with the union is not a problem at all. The union is done at the database side so the union will work properly there with the values. Dictionaries are not meant to be ordered so they will print in any order. – Abdul Aziz Barkat Jan 24 '21 at 07:35
  • @AbdulAzizBarkat could you please use union in Django with annotate (additional fields). You will know what I mean. – AlASAD WAIL Jan 24 '21 at 16:20
  • @AlASADWAIL you need to annotate all your querysets for that also since kwargs are not ordered you need to **chain** the annotations if there are multiple [Django queryset union appears not to be working when combined with .annotate()](https://stackoverflow.com/questions/48028411/django-queryset-union-appears-not-to-be-working-when-combined-with-annotate) – Abdul Aziz Barkat Jan 24 '21 at 16:26

0 Answers0