Home > OS >  Getting the whole object of a related field in django
Getting the whole object of a related field in django

Time:09-30

I have a model like this:

 class Cart(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid4)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True)


class Reception(models.Model):
    PAYMENT_STATUS_PENDING = 'P'
    PAYMENT_STATUS_COMPLETE = 'C'
    PAYMENT_STATUS_FAILED = 'F'
    PAYMENT_STATUS_CHOICES = [
        (PAYMENT_STATUS_PENDING, 'Pending'),
        (PAYMENT_STATUS_COMPLETE, 'Complete'),
        (PAYMENT_STATUS_FAILED, 'Failed')
    ]
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    entry_date = models.DateField()
    total_price = models.IntegerField()
    payment_status = models.CharField(
        max_length=1,
        choices=PAYMENT_STATUS_CHOICES,
        default=PAYMENT_STATUS_PENDING
    )

My question is: How can I get a particular Cart record from the Reception model? I tried using this serializer:

class ReceptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Reception
        fields = ['id', 'customer', 'entry_date', 'payment_status', 'cart']

but it only returns the id of a cart. I want to return the whole object of that specific cart. How can I do that?

CodePudding user response:

If you want to utilize nested serialization, one possible solution would be to define CartSerializer and override the cart field of the ReceptionSerializer class as follows

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = ['id', 'customer']

class ReceptionSerializer(serializers.ModelSerializer):
    cart = CartSerializer(many=True)
    
    class Meta:
        model = Reception
        fields = ['id', 'customer', 'entry_date', 'payment_status', 'cart']

However, please note that the cart field will become read-only this way.

  • Related