Django related_name not querying the data in template












1















I have two models, Transaction and Subscription. Transaction has a FK to Subscription with the related name="subscription_transaction". I am trying to query the transaction.amount on a SubscriptionDetailView. Why is my template query not working.



Neither work



subscription_detail.html



<td  class="text-dark ">{{ subscription.subscription_transaction.timestamp.all }}</td
<td class="text-dark"> {{ subscription.subscription_transaction.amount }}</td>`


models.py



class Subscription(models.Model):
id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, primary_key=True, editable=False)
user_membership = models.ForeignKey(UserMembership, on_delete=models.CASCADE)
stripe_subscription_id = models.CharField(max_length=40)
active = models.BooleanField(default=True)

def __str__(self):
return self.user_membership.user.username

@property
def get_created_date(self):
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
return datetime.fromtimestamp(subscription.created)

@property
def get_next_billing_date(self):
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
return datetime.fromtimestamp(subscription.current_period_end)


class Transaction(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_transaction")
order_id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, primary_key=True, editable=False)
subscription = models.ForeignKey(Subscription, on_delete=models.SET_NULL, null=True, blank=True, related_name="subscription_transaction")
amount = models.DecimalField(max_digits=100, decimal_places=2)
success = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)









share|improve this question























  • subscription.subscription_transaction is a RelatedManager object.

    – Sachin Kukreja
    Nov 16 '18 at 22:03











  • If you want a subscription to be linked with one transaction, then use OneToOneField. In that case, the template you have will work as expected.

    – Sachin Kukreja
    Nov 16 '18 at 22:08
















1















I have two models, Transaction and Subscription. Transaction has a FK to Subscription with the related name="subscription_transaction". I am trying to query the transaction.amount on a SubscriptionDetailView. Why is my template query not working.



Neither work



subscription_detail.html



<td  class="text-dark ">{{ subscription.subscription_transaction.timestamp.all }}</td
<td class="text-dark"> {{ subscription.subscription_transaction.amount }}</td>`


models.py



class Subscription(models.Model):
id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, primary_key=True, editable=False)
user_membership = models.ForeignKey(UserMembership, on_delete=models.CASCADE)
stripe_subscription_id = models.CharField(max_length=40)
active = models.BooleanField(default=True)

def __str__(self):
return self.user_membership.user.username

@property
def get_created_date(self):
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
return datetime.fromtimestamp(subscription.created)

@property
def get_next_billing_date(self):
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
return datetime.fromtimestamp(subscription.current_period_end)


class Transaction(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_transaction")
order_id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, primary_key=True, editable=False)
subscription = models.ForeignKey(Subscription, on_delete=models.SET_NULL, null=True, blank=True, related_name="subscription_transaction")
amount = models.DecimalField(max_digits=100, decimal_places=2)
success = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)









share|improve this question























  • subscription.subscription_transaction is a RelatedManager object.

    – Sachin Kukreja
    Nov 16 '18 at 22:03











  • If you want a subscription to be linked with one transaction, then use OneToOneField. In that case, the template you have will work as expected.

    – Sachin Kukreja
    Nov 16 '18 at 22:08














1












1








1








I have two models, Transaction and Subscription. Transaction has a FK to Subscription with the related name="subscription_transaction". I am trying to query the transaction.amount on a SubscriptionDetailView. Why is my template query not working.



Neither work



subscription_detail.html



<td  class="text-dark ">{{ subscription.subscription_transaction.timestamp.all }}</td
<td class="text-dark"> {{ subscription.subscription_transaction.amount }}</td>`


models.py



class Subscription(models.Model):
id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, primary_key=True, editable=False)
user_membership = models.ForeignKey(UserMembership, on_delete=models.CASCADE)
stripe_subscription_id = models.CharField(max_length=40)
active = models.BooleanField(default=True)

def __str__(self):
return self.user_membership.user.username

@property
def get_created_date(self):
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
return datetime.fromtimestamp(subscription.created)

@property
def get_next_billing_date(self):
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
return datetime.fromtimestamp(subscription.current_period_end)


class Transaction(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_transaction")
order_id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, primary_key=True, editable=False)
subscription = models.ForeignKey(Subscription, on_delete=models.SET_NULL, null=True, blank=True, related_name="subscription_transaction")
amount = models.DecimalField(max_digits=100, decimal_places=2)
success = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)









share|improve this question














I have two models, Transaction and Subscription. Transaction has a FK to Subscription with the related name="subscription_transaction". I am trying to query the transaction.amount on a SubscriptionDetailView. Why is my template query not working.



Neither work



subscription_detail.html



<td  class="text-dark ">{{ subscription.subscription_transaction.timestamp.all }}</td
<td class="text-dark"> {{ subscription.subscription_transaction.amount }}</td>`


models.py



class Subscription(models.Model):
id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, primary_key=True, editable=False)
user_membership = models.ForeignKey(UserMembership, on_delete=models.CASCADE)
stripe_subscription_id = models.CharField(max_length=40)
active = models.BooleanField(default=True)

def __str__(self):
return self.user_membership.user.username

@property
def get_created_date(self):
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
return datetime.fromtimestamp(subscription.created)

@property
def get_next_billing_date(self):
subscription = stripe.Subscription.retrieve(self.stripe_subscription_id)
return datetime.fromtimestamp(subscription.current_period_end)


class Transaction(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="user_transaction")
order_id = models.CharField(max_length=36, unique=True, default=uuid.uuid4, primary_key=True, editable=False)
subscription = models.ForeignKey(Subscription, on_delete=models.SET_NULL, null=True, blank=True, related_name="subscription_transaction")
amount = models.DecimalField(max_digits=100, decimal_places=2)
success = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)






django






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 21:31









Dominic M.Dominic M.

899




899













  • subscription.subscription_transaction is a RelatedManager object.

    – Sachin Kukreja
    Nov 16 '18 at 22:03











  • If you want a subscription to be linked with one transaction, then use OneToOneField. In that case, the template you have will work as expected.

    – Sachin Kukreja
    Nov 16 '18 at 22:08



















  • subscription.subscription_transaction is a RelatedManager object.

    – Sachin Kukreja
    Nov 16 '18 at 22:03











  • If you want a subscription to be linked with one transaction, then use OneToOneField. In that case, the template you have will work as expected.

    – Sachin Kukreja
    Nov 16 '18 at 22:08

















subscription.subscription_transaction is a RelatedManager object.

– Sachin Kukreja
Nov 16 '18 at 22:03





subscription.subscription_transaction is a RelatedManager object.

– Sachin Kukreja
Nov 16 '18 at 22:03













If you want a subscription to be linked with one transaction, then use OneToOneField. In that case, the template you have will work as expected.

– Sachin Kukreja
Nov 16 '18 at 22:08





If you want a subscription to be linked with one transaction, then use OneToOneField. In that case, the template you have will work as expected.

– Sachin Kukreja
Nov 16 '18 at 22:08












2 Answers
2






active

oldest

votes


















1














Since subscription.subscription_transaction is a RelatedManager object, you can get all transactions of the subscription using .all.



Example:



{% for transaction in subscription.subscription_transaction.all %}
Timestamp: {{ transaction.timestamp }},
Amount: {{ transaction.amount }}
{% endfor %}





share|improve this answer































    1














    Notice that Transaction has a ForeignKey to Subscription. That's a one to many relation: Each Transaction row can have up to one Subscription however each Subscription can be related with many Transactions.



    Following this you should now understand that you are able to use the direct relation betwen Transaction and Subscription (i.e from a Transaction instance) directly, i.e you can do something like transaction.subscription.active sincec each transaction will have one subscription. However, to use the reverse relation (i.e from Subscription) you need to properly use the related object manager to enumerate all possible transactions the subscription may have. Remember that Django auto-names the reverse relation object something_set (in your case instead of subscription_transaction you'd have a transaction_set attribute to the Subscription instance); there's a reason for that: To remember that the reverse relation of a foreign key is a set of objects!



    Thus, if you change your template code to something like:



    {% for tr in subscription.subscription_transaction.all %}
    {{ tr.timestamp }}
    {{ tr.amount }}
    {% endfor %}


    it will output all the transactions of the subscription.






    share|improve this answer


























    • Thank you very much for the explaination, I understand now! I would have given you the green check, but your last line is incorrect. It's endfor

      – Dominic M.
      Nov 17 '18 at 0:26











    • You're welcome! I also fixed the error with the last line.

      – Serafeim
      Nov 17 '18 at 8:20











    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',
    autoActivateHeartbeat: false,
    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%2f53345685%2fdjango-related-name-not-querying-the-data-in-template%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Since subscription.subscription_transaction is a RelatedManager object, you can get all transactions of the subscription using .all.



    Example:



    {% for transaction in subscription.subscription_transaction.all %}
    Timestamp: {{ transaction.timestamp }},
    Amount: {{ transaction.amount }}
    {% endfor %}





    share|improve this answer




























      1














      Since subscription.subscription_transaction is a RelatedManager object, you can get all transactions of the subscription using .all.



      Example:



      {% for transaction in subscription.subscription_transaction.all %}
      Timestamp: {{ transaction.timestamp }},
      Amount: {{ transaction.amount }}
      {% endfor %}





      share|improve this answer


























        1












        1








        1







        Since subscription.subscription_transaction is a RelatedManager object, you can get all transactions of the subscription using .all.



        Example:



        {% for transaction in subscription.subscription_transaction.all %}
        Timestamp: {{ transaction.timestamp }},
        Amount: {{ transaction.amount }}
        {% endfor %}





        share|improve this answer













        Since subscription.subscription_transaction is a RelatedManager object, you can get all transactions of the subscription using .all.



        Example:



        {% for transaction in subscription.subscription_transaction.all %}
        Timestamp: {{ transaction.timestamp }},
        Amount: {{ transaction.amount }}
        {% endfor %}






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 22:06









        Sachin KukrejaSachin Kukreja

        2,0451716




        2,0451716

























            1














            Notice that Transaction has a ForeignKey to Subscription. That's a one to many relation: Each Transaction row can have up to one Subscription however each Subscription can be related with many Transactions.



            Following this you should now understand that you are able to use the direct relation betwen Transaction and Subscription (i.e from a Transaction instance) directly, i.e you can do something like transaction.subscription.active sincec each transaction will have one subscription. However, to use the reverse relation (i.e from Subscription) you need to properly use the related object manager to enumerate all possible transactions the subscription may have. Remember that Django auto-names the reverse relation object something_set (in your case instead of subscription_transaction you'd have a transaction_set attribute to the Subscription instance); there's a reason for that: To remember that the reverse relation of a foreign key is a set of objects!



            Thus, if you change your template code to something like:



            {% for tr in subscription.subscription_transaction.all %}
            {{ tr.timestamp }}
            {{ tr.amount }}
            {% endfor %}


            it will output all the transactions of the subscription.






            share|improve this answer


























            • Thank you very much for the explaination, I understand now! I would have given you the green check, but your last line is incorrect. It's endfor

              – Dominic M.
              Nov 17 '18 at 0:26











            • You're welcome! I also fixed the error with the last line.

              – Serafeim
              Nov 17 '18 at 8:20
















            1














            Notice that Transaction has a ForeignKey to Subscription. That's a one to many relation: Each Transaction row can have up to one Subscription however each Subscription can be related with many Transactions.



            Following this you should now understand that you are able to use the direct relation betwen Transaction and Subscription (i.e from a Transaction instance) directly, i.e you can do something like transaction.subscription.active sincec each transaction will have one subscription. However, to use the reverse relation (i.e from Subscription) you need to properly use the related object manager to enumerate all possible transactions the subscription may have. Remember that Django auto-names the reverse relation object something_set (in your case instead of subscription_transaction you'd have a transaction_set attribute to the Subscription instance); there's a reason for that: To remember that the reverse relation of a foreign key is a set of objects!



            Thus, if you change your template code to something like:



            {% for tr in subscription.subscription_transaction.all %}
            {{ tr.timestamp }}
            {{ tr.amount }}
            {% endfor %}


            it will output all the transactions of the subscription.






            share|improve this answer


























            • Thank you very much for the explaination, I understand now! I would have given you the green check, but your last line is incorrect. It's endfor

              – Dominic M.
              Nov 17 '18 at 0:26











            • You're welcome! I also fixed the error with the last line.

              – Serafeim
              Nov 17 '18 at 8:20














            1












            1








            1







            Notice that Transaction has a ForeignKey to Subscription. That's a one to many relation: Each Transaction row can have up to one Subscription however each Subscription can be related with many Transactions.



            Following this you should now understand that you are able to use the direct relation betwen Transaction and Subscription (i.e from a Transaction instance) directly, i.e you can do something like transaction.subscription.active sincec each transaction will have one subscription. However, to use the reverse relation (i.e from Subscription) you need to properly use the related object manager to enumerate all possible transactions the subscription may have. Remember that Django auto-names the reverse relation object something_set (in your case instead of subscription_transaction you'd have a transaction_set attribute to the Subscription instance); there's a reason for that: To remember that the reverse relation of a foreign key is a set of objects!



            Thus, if you change your template code to something like:



            {% for tr in subscription.subscription_transaction.all %}
            {{ tr.timestamp }}
            {{ tr.amount }}
            {% endfor %}


            it will output all the transactions of the subscription.






            share|improve this answer















            Notice that Transaction has a ForeignKey to Subscription. That's a one to many relation: Each Transaction row can have up to one Subscription however each Subscription can be related with many Transactions.



            Following this you should now understand that you are able to use the direct relation betwen Transaction and Subscription (i.e from a Transaction instance) directly, i.e you can do something like transaction.subscription.active sincec each transaction will have one subscription. However, to use the reverse relation (i.e from Subscription) you need to properly use the related object manager to enumerate all possible transactions the subscription may have. Remember that Django auto-names the reverse relation object something_set (in your case instead of subscription_transaction you'd have a transaction_set attribute to the Subscription instance); there's a reason for that: To remember that the reverse relation of a foreign key is a set of objects!



            Thus, if you change your template code to something like:



            {% for tr in subscription.subscription_transaction.all %}
            {{ tr.timestamp }}
            {{ tr.amount }}
            {% endfor %}


            it will output all the transactions of the subscription.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 17 '18 at 8:19

























            answered Nov 16 '18 at 22:06









            SerafeimSerafeim

            10.2k964115




            10.2k964115













            • Thank you very much for the explaination, I understand now! I would have given you the green check, but your last line is incorrect. It's endfor

              – Dominic M.
              Nov 17 '18 at 0:26











            • You're welcome! I also fixed the error with the last line.

              – Serafeim
              Nov 17 '18 at 8:20



















            • Thank you very much for the explaination, I understand now! I would have given you the green check, but your last line is incorrect. It's endfor

              – Dominic M.
              Nov 17 '18 at 0:26











            • You're welcome! I also fixed the error with the last line.

              – Serafeim
              Nov 17 '18 at 8:20

















            Thank you very much for the explaination, I understand now! I would have given you the green check, but your last line is incorrect. It's endfor

            – Dominic M.
            Nov 17 '18 at 0:26





            Thank you very much for the explaination, I understand now! I would have given you the green check, but your last line is incorrect. It's endfor

            – Dominic M.
            Nov 17 '18 at 0:26













            You're welcome! I also fixed the error with the last line.

            – Serafeim
            Nov 17 '18 at 8:20





            You're welcome! I also fixed the error with the last line.

            – Serafeim
            Nov 17 '18 at 8:20


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53345685%2fdjango-related-name-not-querying-the-data-in-template%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()