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.

Automated related ForeignKey Models in ModelSchema

See original GitHub issue

Can related models be handled automatically?

Model

class ExampleModel(models.Model):
    relation = models.ForeignKey(SomeOtherModel, on_delete=models.PROTECT, related_name='example')

ModelSchema

class ExampleSchema(ModelSchema):
   class Config:
       model = models.ExampleModel
       model_fields = ['id', 'relation']

API

@api.post('/example')
def create_example(request, payload: schemas.ExampleSchema):
    pl = payload.dict()
    relation = get_object_or_404(SomeOtherModel, id=payload.relation)
    pl['relation'] = relation
    example = models.ExampleModel.objects.create(**pl)
    return {'id': example.id}

The above example works with the payload {'relation_id': 4} if the object with ID 4 exists.

Question 1 Is there any specific reason why the field has to be named relation_id in the payload and not just relation?

Question 2 In the API, is it really necessary to do

    pl = payload.dict()
    relation = get_object_or_404(SomeOtherModel, id=payload.relation)
    pl['relation'] = relation

or can that be somehow done automatically? It seems that writing the get_object_or_404() is currently needed, or can that be omitted with an other apporach?

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
chrisbodoncommented, Aug 19, 2022

I´m using that workaround but it gets this when I try to post:

ValueError: Cannot assign "18": "Activity.town" must be a "Town" instance.

My code:

URLS.PY

@api.post("/activities", response=ActivitySchema)
def create_activities(request, data: ActivitySchema):
	obj = Activity.objects.create(**data.dict())
	return obj

The data Im trying to post

{icon_id: '6', name: 'mn bnb', highlight: false, town_id: 18}

SCHEMAS.PY

class ActivitySchema(ModelSchema):
	town_id: int = None
	icon_id: int = None
	
	class Config:
		model = Activity
		model_fields = "__all__"

MODELS.PY

class Activity(models.Model):
	town = models.ForeignKey(Town, on_delete=models.CASCADE, null=False)
	icon = models.ForeignKey(MediaIcon, on_delete=models.CASCADE, null=False)
	name = models.CharField(max_length=255, null=False)
	highlight = models.BooleanField(default=False)
	
	def __str__(self):
		return self.name
1reaction
vitalikcommented, Jun 7, 2022

@fantasticle

… This will yield a ninja.errors.ConfigError: Field(s) {‘my_field’} are not in model.

I think it should not - can you give your example ?

Maybe workaround for you case would be to set FK ids as attributes:

class MyModelSchema(ModelSchema):
  some_relation_id: int
  other_relation_id: int
  class Config:
    model = MyModel
    fields = ['some_char_field']
...

@api.post(...)
def foo(request, payload: MyModelSchema)
      obj = MyModel(**payload.dict())
      obj.save()

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using South to convert ForeignKey TO ManyToManyField not ...
I am using South to change a ForeignKey TO ManyToManyField in one of the models in Django but it is not working out...
Read more >
Fluent → Schema - Vapor Docs
Foreign key actions happen solely in the database, bypassing Fluent. This means things like model middleware and soft-delete may not work correctly. Dictionary¶....
Read more >
DbSchema Features
DbSchema model contains its own image of the schema, independent from the database. Connecting to another database won't change the model schema unless...
Read more >
Models — Tortoise ORM v0.17.3 Documentation
To get working with models, first you should import them ... that we require that direct filters be applied to the DB-backing field...
Read more >
Defining a Schema - Django Ninja
Imagine we have a Task Django model with a User ForeignKey: from django.db import models class Task(models.Model): title = models.
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