1

I'm new in django and a simple query blocks me..

So, here is a slice of my model:

class History(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    name      = models.CharField(max_length=200)
    user      = models.ForeignKey(User)
    state     = models.ForeignKey(Status)
    reason    = models.TextField()
    gpgkey    = models.ForeignKey(Key)

def __unicode__(self):
    return self.name

class Key(models.Model):
    gpgkey     = models.CharField(max_length=128)
    gpgid       = models.CharField(max_length=32)
    path        = models.CharField(max_length=200)

    def __unicode__(self):
        return self.gpgkey

this query History.objects.filter(pk=1).values() returns:

[{'user_id': 1, 'name': u'test-4.30-6', 'timestamp': datetime.datetime(2015, 1, 1, 20, 2, 0, 578794, tzinfo=<UTC>), 'gpgkey_id': 1, 'reason': u'blablabla', 'state_id': 2, u'id': 1}]

Target is, that for ex. gpgkey_id is gpgkey : { gpgkey : "test", gpgid : "06B7FFF" } and so on for all the other related objects. How can i do that?

I use values(), because I want the Fields and not the whole model.

njoy
  • 11
  • 1
  • You can use JSON. Here you find more information: http://stackoverflow.com/a/15538391/2154023 – torm Jan 02 '15 at 15:46
  • 1
    Why do you want the fields and not the model instance? Don't use `values()` unless you explicitly need a dictionary of `key:value` items, and you are 100% sure you don't need any of the model methods. – knbk Jan 02 '15 at 15:48
  • 1
    i want to send it back (api like), so i want only the values and not the model. – njoy Jan 02 '15 at 16:07
  • 1
    That's better suited to a serializer like @torm mentioned. Check out the django docs on [serialization](https://docs.djangoproject.com/en/1.7/topics/serialization/). Also, you should check out [django rest framework](http://www.django-rest-framework.org/) or [tastypie](https://django-tastypie.readthedocs.org/en/latest/) for building the actual API, both are great frameworks to easily create an API. – knbk Jan 02 '15 at 16:13

1 Answers1

0

you have to ask for them in the values method parameters, and unfortunately I think you must specify also the default you want for you starting model:

History.objects.filter(pk=1).values('gpgkey__gpgkey', 'gpgkey__gpgid', 'gpgkey__path', 'timestamp', 'name', 'user', 'state', 'reason')

if you have a long list of attributes something better can be made traversing the _meta.fields attribute of your model and building that parameter list from there, but the base idea is the previous one.

DRC
  • 4,898
  • 2
  • 21
  • 35