-
-
Notifications
You must be signed in to change notification settings - Fork 423
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Automated related ForeignKey Models in ModelSchema #444
Comments
well the philosophy for incoming payloads are only to validate types/structure but the database calls should happen inside the controller function Maybe try doing this (relation_id instead of relation): class ExampleSchema(ModelSchema):
class Config:
model = models.ExampleModel
model_fields = ['id', 'relation_id'] # !!!
...
ExampleModel.objects.create(**pl) # I think this should validate relation_id automatically ? |
Hi @21adrian1996 and @vitalik
This will yield a I found one workaround to check if the field is an FK-field via class MyModelSchema(ModelSchema):
class Config:
model = MyModel
model_exclude = [ ... ] # lots of exclusions here for safety reasons
@router.post("add")
def add(request, payload: MyModelSchema):
my_instance = MyModel()
for k,v in payload.dict().items():
if my_instance._meta.get_field(k).is_relation:
target_model = my_instance._meta.get_field(k).target_field.model
v = target_model.objects.get(pk=v)
my_instance.__setattr__(k,v)
my_instance.save() Do you think this would be a good enhancement? I like the way Django handles database tables in the backend but appending/using |
@fantasticle
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() |
I had the same problem and your workaround using attributes works perfectly fine! |
I´m using that workaround but it gets this when I try to post:
My code: URLS.PY
The data Im trying to post
SCHEMAS.PY
MODELS.PY
|
I have the same problem as you. |
I also tried the first approach to receive the same error the second option with attributes worked for me too! |
Can related models be handled automatically?
Model
ModelSchema
API
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 justrelation
?Question 2
In the API, is it really necessary to do
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?The text was updated successfully, but these errors were encountered: