Home > Mobile >  Django ORM get all fields value. (foreign keys)
Django ORM get all fields value. (foreign keys)

Time:07-21

class MyUser(models.Model):
     name = models.CharField(max_length=10)

class Foo(models.Model):
    my_user = models.ForeignKey(MyUser,on_delete=models.CASCADE)
    text = models.CharField(max_length=25)

Let's say we have two models like this. I want to get all fields with an ORM query from the MyUser model. Like this:

{
 "name":"example"
 "Foo":{
      "text":"example-text",
      "text":"example_text2"    
   } 
}

How should I write a query to do this?

MyUser.objects.all() # But give it ALL FIELDS   RELEATED FIELDS

CodePudding user response:

I don't think you can return two responses like that. I would have to be two separate queries. Try referring to Django: objects and model_set

CodePudding user response:

You don't necessarily need a special queryset or filter to do that, but note that your Many-to-One relation means that MyUser can have lots of Foo objects:

my_user = MyUser.objects.get(...) # get the user by PK or some other means

# get all Foos related to my_user
my_user.foo_set.all()

# get the first Foo related to my user
my_user.foo_set.first()

# get the text from the first Foo
my_user.foo_set.first().text

# get the Foos which have text 'example-text'
my_user.foo_set.filter(text='example-text')

You can access some of these in Django templates as well:

{{ my_user.foo_set.first.text }}

{% for foo in my_user.foo_set.all }}
   {{ foo.text }}
{% endfor %}

If you wanted to create a dict then you can just loop through the reverse accessor and append the field/key values to your ['Foo'] key quite easily.

  • Related