-
With these models class User(models.Model):
id = models.PositiveSmallIntegerField(primary_key=True)
class Product(models.Model):
id = models.PositiveSmallIntegerField(primary_key=True)
name = models.CharField(max_length=255)
public_id = models.UUIDField()
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Sale(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE) If I have and enpoint that allows a user to create an Sale, how do I make sure that the product the sale will have belongs to that user? So it's not only a custom queryset for the In DRF, this would be a custom RelatedField with a queryset argument, but I have no idea how this is done in Django Ninja or Pydantic. I'm kinda guessing is this feature in pydantic V2, which is soon to be supported in stable with django-ninja. Is there a workaround for Pydantic V1? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
well to me this looks like a business logic that you should do inside a view function... I guess something like this: class SalePayload(Schema):
product_id: int
@api.post("/sales")
def create_sale(request, payload: SalePayload):
product = get_object_or_404(Product.objects.filter(owner=request.user), id=payload.product_id)
# ^ this will return 404 if user tries to create a sale with product that not owner of
Sale.objects.create(product) |
Beta Was this translation helpful? Give feedback.
maybe like this:
that's for ninja v0.x probably the most logical way
in django ninja v1.0 (
pip install django-ninja==1.0rc0
) and pydantic2you can create your own validator and it will take request in context