Skip to content

How to filter foreign key fields on input schema based on the user #910

Answered by vitalik
alexgmin asked this question in Q&A
Discussion options

You must be logged in to vote

maybe like this:

class SalePayload(Schema):
    product_id: int

@api.post("/sales")
def create_sale(request, payload: SalePayload):
     qs = Product.objects.filter(owner=request.user)
     try:
          product = qs.get(id=payload.product_id)
     except Product.DoesNotExist:
          raise ValidationError(details...)
     Sale.objects.create(product)

that's for ninja v0.x probably the most logical way

in django ninja v1.0 (pip install django-ninja==1.0rc0) and pydantic2

you can create your own validator and it will take request in context

class SalePayload(Schema):
    product_id: int

    @field_validator('product_id')
    @classmethod
    def validate_product_id(cls, v: int, info):…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@alexgmin
Comment options

@vitalik
Comment options

Answer selected by alexgmin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants