Tom
Tom

Reputation: 183

Unable to call a class using Django

If I do that :

from myapp import models
User.objects.first()

I got that error :

NameError : name 'User' is not defined

whereas if I do that

import myapp
myapp.models.User.objects.first()

it works

I don't understand at all why I have that problem

Thank you very much for your help !

Upvotes: 0

Views: 43

Answers (2)

Amin
Amin

Reputation: 2853

In your example, your have not imported class User actually. You have imported it's module called models You can do one of these:

from myapp import models
models.User.objects.first()

Or:

from myapp.models import User
User.objects.first()

Upvotes: 0

oreopot
oreopot

Reputation: 3450

Replace:

from myapp import models

with the following:

This way, you are telling Django which model classes to import rather than leaving Django guessing what to do with it.

It prevents you from loading unnecessary models which might not be used right away and could potentially increase load time.

from myapp.models import User

Upvotes: 1

Related Questions