Create Schema in resolve function #1403
-
Hi. Here are the models: class AbstractProduct(models.Model):
class Meta:
abstract = True
reference = models.TextField()
class Product1(AbstractProduct):
pass
class Product2(AbstractProduct):
pass
# a billion Product subclasses..
class OrderProduct(models.Models):
content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
object_id = models.PositiveIntegerField(db_index=True)
product = GenericForeignKey("content_type", "object_id")
class Order(model.Models):
order_product = models.ForeignKey(OrderProduct, ...) and schema class ProductOut(ModelSchema):
class Meta:
model = AbstractProduct
fields = ("reference",)
id: int
@staticmethod
def resolve_id(product: AbstractProduct):
return product.id According to my debugger, I'm executing these function, but I get errors like:
My views are nothing specials: @router.get('/{reference}', response=OrderOut)
def order_get(request, reference: str):
try:
return Order.objects.get(reference=reference)
except Order.DoesNotExist as e:
raise Http404() from e So maybe I'm missing something or using the api wrong. I tried calling the Thanks 🙏 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I'm replying with the answer. As I'm re-reading my question, I forgot the here is the version I had: class OrderOut(ModelSchema):
class Meta:
model = Order
fields = ("reference", ...)
product: ProductOut
@staticmethod
def resolve_product(order: Order) -> ProductOut:
return ProductOut.model_validate(order.order_product.product) After reading stack traces and running the debugger I found the problem, Ninja ModelSchema will take care of the class OrderOut(ModelSchema):
class Meta:
model = Order
fields = ("reference", ...)
product: ProductOut
@staticmethod
def resolve_product(order: Order) -> ProductType:
return order.order_product.product
# or
class OrderOut(ModelSchema):
class Meta:
model = Order
fields = ("reference", ...)
product: ProductOut = Field(..., alias="order_product.product") |
Beta Was this translation helpful? Give feedback.
I'm replying with the answer.
As I'm re-reading my question, I forgot the
OrderOut
Schema, which was the culprit here.here is the version I had:
After reading stack traces and running the debugger I found the problem, Ninja ModelSchema will take care of the
model_validate
for me.So, 2 versions that worked: