ListCreateAPIView POST with an annotated field that's in serializer not model











up vote
0
down vote

favorite












I'm building a simple budgeting app to work on learning Django & React. I've used DRF to build an API to create and get transactions from the database. I'm currently calculating the total running balance on the fly when I do my GET. This has been working well, but when I do a POST I get an error that my dynamic balance field is required since that field is in my serializer. How can I get around this?



views.py



class CreateView(generics.ListCreateAPIView):
"""This class defines the GET & POST behavior of the rest api."""

queryset = Transaction.objects.all()

# This is the balance that's calculated on the fly
queryset_with_balance = queryset.annotate(balance=Window(Sum('amount'),
order_by=F('created_time').asc())).all().order_by('-created_time')

serializer_class = TransactionSerializer

def perform_create(self, serializer):
"""Save the post data when creating a new transaction."""
serializer.save()

def get_queryset(self):
return self.queryset_with_balance


serializers.py



class TransactionSerializer(serializers.ModelSerializer):
balance = serializers.DecimalField(decimal_places=2, max_digits=19)

class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Transaction
fields = ('id', 'date', 'payee', 'category',
'amount', 'balance', 'created_time', 'modified_time')


models.py



class Transaction(models.Model):
date = models.DateField()
payee = models.CharField(max_length=256)
category = models.CharField(max_length=256)
amount = MoneyField(max_digits=19,
decimal_places=2,
default_currency='USD')
created_time = models.DateTimeField(auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)









share|improve this question
























  • Do you need this balance field while HTTP POST ?
    – JPG
    Nov 5 at 2:49










  • you can move queryset_with_balance or only annotate to def get_queryset(self):
    – Ngoc Pham
    Nov 5 at 2:50










  • Balance is only needed on the GET. I'm not storing that in the DB.
    – brewcrazy
    Nov 5 at 2:53










  • @brewcrazy Check my answer below :) Hope that will solve the issue :)
    – JPG
    Nov 5 at 2:58















up vote
0
down vote

favorite












I'm building a simple budgeting app to work on learning Django & React. I've used DRF to build an API to create and get transactions from the database. I'm currently calculating the total running balance on the fly when I do my GET. This has been working well, but when I do a POST I get an error that my dynamic balance field is required since that field is in my serializer. How can I get around this?



views.py



class CreateView(generics.ListCreateAPIView):
"""This class defines the GET & POST behavior of the rest api."""

queryset = Transaction.objects.all()

# This is the balance that's calculated on the fly
queryset_with_balance = queryset.annotate(balance=Window(Sum('amount'),
order_by=F('created_time').asc())).all().order_by('-created_time')

serializer_class = TransactionSerializer

def perform_create(self, serializer):
"""Save the post data when creating a new transaction."""
serializer.save()

def get_queryset(self):
return self.queryset_with_balance


serializers.py



class TransactionSerializer(serializers.ModelSerializer):
balance = serializers.DecimalField(decimal_places=2, max_digits=19)

class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Transaction
fields = ('id', 'date', 'payee', 'category',
'amount', 'balance', 'created_time', 'modified_time')


models.py



class Transaction(models.Model):
date = models.DateField()
payee = models.CharField(max_length=256)
category = models.CharField(max_length=256)
amount = MoneyField(max_digits=19,
decimal_places=2,
default_currency='USD')
created_time = models.DateTimeField(auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)









share|improve this question
























  • Do you need this balance field while HTTP POST ?
    – JPG
    Nov 5 at 2:49










  • you can move queryset_with_balance or only annotate to def get_queryset(self):
    – Ngoc Pham
    Nov 5 at 2:50










  • Balance is only needed on the GET. I'm not storing that in the DB.
    – brewcrazy
    Nov 5 at 2:53










  • @brewcrazy Check my answer below :) Hope that will solve the issue :)
    – JPG
    Nov 5 at 2:58













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm building a simple budgeting app to work on learning Django & React. I've used DRF to build an API to create and get transactions from the database. I'm currently calculating the total running balance on the fly when I do my GET. This has been working well, but when I do a POST I get an error that my dynamic balance field is required since that field is in my serializer. How can I get around this?



views.py



class CreateView(generics.ListCreateAPIView):
"""This class defines the GET & POST behavior of the rest api."""

queryset = Transaction.objects.all()

# This is the balance that's calculated on the fly
queryset_with_balance = queryset.annotate(balance=Window(Sum('amount'),
order_by=F('created_time').asc())).all().order_by('-created_time')

serializer_class = TransactionSerializer

def perform_create(self, serializer):
"""Save the post data when creating a new transaction."""
serializer.save()

def get_queryset(self):
return self.queryset_with_balance


serializers.py



class TransactionSerializer(serializers.ModelSerializer):
balance = serializers.DecimalField(decimal_places=2, max_digits=19)

class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Transaction
fields = ('id', 'date', 'payee', 'category',
'amount', 'balance', 'created_time', 'modified_time')


models.py



class Transaction(models.Model):
date = models.DateField()
payee = models.CharField(max_length=256)
category = models.CharField(max_length=256)
amount = MoneyField(max_digits=19,
decimal_places=2,
default_currency='USD')
created_time = models.DateTimeField(auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)









share|improve this question















I'm building a simple budgeting app to work on learning Django & React. I've used DRF to build an API to create and get transactions from the database. I'm currently calculating the total running balance on the fly when I do my GET. This has been working well, but when I do a POST I get an error that my dynamic balance field is required since that field is in my serializer. How can I get around this?



views.py



class CreateView(generics.ListCreateAPIView):
"""This class defines the GET & POST behavior of the rest api."""

queryset = Transaction.objects.all()

# This is the balance that's calculated on the fly
queryset_with_balance = queryset.annotate(balance=Window(Sum('amount'),
order_by=F('created_time').asc())).all().order_by('-created_time')

serializer_class = TransactionSerializer

def perform_create(self, serializer):
"""Save the post data when creating a new transaction."""
serializer.save()

def get_queryset(self):
return self.queryset_with_balance


serializers.py



class TransactionSerializer(serializers.ModelSerializer):
balance = serializers.DecimalField(decimal_places=2, max_digits=19)

class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = Transaction
fields = ('id', 'date', 'payee', 'category',
'amount', 'balance', 'created_time', 'modified_time')


models.py



class Transaction(models.Model):
date = models.DateField()
payee = models.CharField(max_length=256)
category = models.CharField(max_length=256)
amount = MoneyField(max_digits=19,
decimal_places=2,
default_currency='USD')
created_time = models.DateTimeField(auto_now_add=True)
modified_time = models.DateTimeField(auto_now=True)






django django-rest-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 5 at 2:50









eyllanesc

66.2k82952




66.2k82952










asked Nov 5 at 2:44









brewcrazy

8911




8911












  • Do you need this balance field while HTTP POST ?
    – JPG
    Nov 5 at 2:49










  • you can move queryset_with_balance or only annotate to def get_queryset(self):
    – Ngoc Pham
    Nov 5 at 2:50










  • Balance is only needed on the GET. I'm not storing that in the DB.
    – brewcrazy
    Nov 5 at 2:53










  • @brewcrazy Check my answer below :) Hope that will solve the issue :)
    – JPG
    Nov 5 at 2:58


















  • Do you need this balance field while HTTP POST ?
    – JPG
    Nov 5 at 2:49










  • you can move queryset_with_balance or only annotate to def get_queryset(self):
    – Ngoc Pham
    Nov 5 at 2:50










  • Balance is only needed on the GET. I'm not storing that in the DB.
    – brewcrazy
    Nov 5 at 2:53










  • @brewcrazy Check my answer below :) Hope that will solve the issue :)
    – JPG
    Nov 5 at 2:58
















Do you need this balance field while HTTP POST ?
– JPG
Nov 5 at 2:49




Do you need this balance field while HTTP POST ?
– JPG
Nov 5 at 2:49












you can move queryset_with_balance or only annotate to def get_queryset(self):
– Ngoc Pham
Nov 5 at 2:50




you can move queryset_with_balance or only annotate to def get_queryset(self):
– Ngoc Pham
Nov 5 at 2:50












Balance is only needed on the GET. I'm not storing that in the DB.
– brewcrazy
Nov 5 at 2:53




Balance is only needed on the GET. I'm not storing that in the DB.
– brewcrazy
Nov 5 at 2:53












@brewcrazy Check my answer below :) Hope that will solve the issue :)
– JPG
Nov 5 at 2:58




@brewcrazy Check my answer below :) Hope that will solve the issue :)
– JPG
Nov 5 at 2:58












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










set balance field as read_only as below,



class TransactionSerializer(serializers.ModelSerializer):
balance = serializers.DecimalField(decimal_places=2, max_digits=19, read_only=True)
# your code





From the DRF doc




Read-only fields are included in the API output, but should not be included in the input during create or update operations.







share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53147657%2flistcreateapiview-post-with-an-annotated-field-thats-in-serializer-not-model%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    set balance field as read_only as below,



    class TransactionSerializer(serializers.ModelSerializer):
    balance = serializers.DecimalField(decimal_places=2, max_digits=19, read_only=True)
    # your code





    From the DRF doc




    Read-only fields are included in the API output, but should not be included in the input during create or update operations.







    share|improve this answer

























      up vote
      1
      down vote



      accepted










      set balance field as read_only as below,



      class TransactionSerializer(serializers.ModelSerializer):
      balance = serializers.DecimalField(decimal_places=2, max_digits=19, read_only=True)
      # your code





      From the DRF doc




      Read-only fields are included in the API output, but should not be included in the input during create or update operations.







      share|improve this answer























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        set balance field as read_only as below,



        class TransactionSerializer(serializers.ModelSerializer):
        balance = serializers.DecimalField(decimal_places=2, max_digits=19, read_only=True)
        # your code





        From the DRF doc




        Read-only fields are included in the API output, but should not be included in the input during create or update operations.







        share|improve this answer












        set balance field as read_only as below,



        class TransactionSerializer(serializers.ModelSerializer):
        balance = serializers.DecimalField(decimal_places=2, max_digits=19, read_only=True)
        # your code





        From the DRF doc




        Read-only fields are included in the API output, but should not be included in the input during create or update operations.








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 5 at 2:55









        JPG

        11.8k2829




        11.8k2829






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53147657%2flistcreateapiview-post-with-an-annotated-field-thats-in-serializer-not-model%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()