question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] ModelSchema with OneToOneField relation error

See original GitHub issue

Describe the bug Models that are OneToOne related are producing an RelatedObjectDoesNotExist error using ModelSchema.

# models.py
class User(models.Model):
    email = models.EmailField(unique=True)
    
class Account(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    username = models.CharField(max_length=15)

    @property
    def full_repr(self):
        return f'{self.username} <{self.user.email}>'
        

# schemas.py
class AccountSchema(ModelSchema):
    full_repr: str = None
    
    class Config:
        model = Account
        model_exclude = ['id', 'user']


class UserSchema(ModelSchema):
    account: AccountSchema = None

    class Config:
        model = User

# routes.py
class AuthBearer(HttpBearer):
    def authenticate(self, request, token):
        token = get_session(key)
        if token:
            return get_object_or_404(User, pk=token.user_id, is_active=True)


@router.get('/', auth=AuthBearer(), response=UserSchema)
def user_detail(request):
    return request.user

This code produces the following exceptions:

Unauthorized: /api/accounts/sessions/
'User' object has no attribute 'template'
Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 54, in __getitem__
    item = getattr(self._obj, key)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__
    raise self.RelatedObjectDoesNotExist(
accounts.models.user.User.account.RelatedObjectDoesNotExist: User has no account.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/template/base.py", line 862, in _resolve_lookup
    current = current[bit]
TypeError: 'User' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/template/base.py", line 870, in _resolve_lookup
    current = getattr(current, bit)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__
    raise self.RelatedObjectDoesNotExist(
accounts.models.user.User.account.RelatedObjectDoesNotExist: User has no account.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/operation.py", line 100, in run
    return self._result_to_response(request, result)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/operation.py", line 193, in _result_to_response
    result = response_model.from_orm(resp_object).dict(
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 161, in from_orm
    return super().from_orm(obj)
  File "pydantic/main.py", line 562, in pydantic.main.BaseModel.from_orm
  File "pydantic/main.py", line 1022, in pydantic.main.validate_model
  File "pydantic/fields.py", line 854, in pydantic.fields.ModelField.validate
  File "pydantic/fields.py", line 1071, in pydantic.fields.ModelField._validate_singleton
  File "pydantic/fields.py", line 1118, in pydantic.fields.ModelField._apply_validators
  File "pydantic/class_validators.py", line 313, in pydantic.class_validators._generic_validator_basic.lambda12
  File "pydantic/main.py", line 678, in pydantic.main.BaseModel.validate
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 161, in from_orm
    return super().from_orm(obj)
  File "pydantic/main.py", line 562, in pydantic.main.BaseModel.from_orm
  File "pydantic/main.py", line 1001, in pydantic.main.validate_model
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 67, in get
    return self[key]
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 58, in __getitem__
    item = Variable(key).resolve(self._obj)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/template/base.py", line 829, in resolve
    value = self._resolve_lookup(context)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/template/base.py", line 910, in _resolve_lookup
    current = context.template.engine.string_if_invalid
AttributeError: 'User' object has no attribute 'template'
Internal Server Error: /api/accounts/sessions/
'User' object has no attribute 'template'
Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 54, in __getitem__
    item = getattr(self._obj, key)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__
    raise self.RelatedObjectDoesNotExist(
accounts.models.user.User.account.RelatedObjectDoesNotExist: User has no account.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/template/base.py", line 862, in _resolve_lookup
    current = current[bit]
TypeError: 'User' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/template/base.py", line 870, in _resolve_lookup
    current = getattr(current, bit)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 421, in __get__
    raise self.RelatedObjectDoesNotExist(
accounts.models.user.User.account.RelatedObjectDoesNotExist: User has no account.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/operation.py", line 100, in run
    return self._result_to_response(request, result)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/operation.py", line 193, in _result_to_response
    result = response_model.from_orm(resp_object).dict(
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 161, in from_orm
    return super().from_orm(obj)
  File "pydantic/main.py", line 562, in pydantic.main.BaseModel.from_orm
  File "pydantic/main.py", line 1022, in pydantic.main.validate_model
  File "pydantic/fields.py", line 854, in pydantic.fields.ModelField.validate
  File "pydantic/fields.py", line 1071, in pydantic.fields.ModelField._validate_singleton
  File "pydantic/fields.py", line 1118, in pydantic.fields.ModelField._apply_validators
  File "pydantic/class_validators.py", line 313, in pydantic.class_validators._generic_validator_basic.lambda12
  File "pydantic/main.py", line 678, in pydantic.main.BaseModel.validate
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 161, in from_orm
    return super().from_orm(obj)
  File "pydantic/main.py", line 562, in pydantic.main.BaseModel.from_orm
  File "pydantic/main.py", line 1001, in pydantic.main.validate_model
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 67, in get
    return self[key]
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/ninja/schema.py", line 58, in __getitem__
    item = Variable(key).resolve(self._obj)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/template/base.py", line 829, in resolve
    value = self._resolve_lookup(context)
  File "/root/.local/share/virtualenvs/app-4PlAip0Q/lib/python3.8/site-packages/django/template/base.py", line 910, in _resolve_lookup
    current = context.template.engine.string_if_invalid
AttributeError: 'User' object has no attribute 'template'
Internal Server Error: /api/accounts/sessions/

Versions (please complete the following information):

  • Python version: 3.8.12
  • Django version: 4.0.2
  • Django-Ninja version: 0.17.0

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
vitalikcommented, Feb 8, 2022

yeah, I guess this is the best solution for now for OneToOneField case

0reactions
gabrielfgulartecommented, Feb 8, 2022

I have a workaround. If I put a resolver on the Schema using hasattr it works:

class UserSchema(ModelSchema):
    account: Optional[AccountSchema] = None

    class Config:
        model = User
    
    @staticmethod
    def resolve_account(obj):
        if hasattr(obj, 'account'):
            return obj.account
        return None
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to solve this django OneToOneField model error?
It looks like this is a by-product of a circular import somewhere. Try changing to feedstock = models.OneToOneField("dashboard.
Read more >
Changelog - Tortoise ORM v0.19.3 Documentation
Fixed ORA-01435 error while using Oracle database (#1155) ... Fix bug in nested QuerySet and Manager . (#864) ... Fixed prefetching over OneToOne...
Read more >
[Solved]-Django error page with DEBUG=True much more ...
I would prefer using sentry as bug reporting tool. It is quick to setup and easy to use. It adds lot of meaningful...
Read more >
Atlas Content Modeler – WordPress plugin
Adding a Relationship field to a content model. This allows you to create relationships between. One-click access to querying content models in WPGraphQL's ......
Read more >
OneToOneField bug fixed - Google Groups
I've fixed the longstanding OneToOneField bug. If you're using ... I'm getting this error when opening user details list. Request Method: GET
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found