Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

django - How to query only the pending interest and not interest that is already accepted/declined?

How to query only the pending interest and not interest that is already accepted/declined? Currently, i am able to query the number of interests that has been submitted. How can I query only the interest that has the status on pending and not accept/decline for my views?

I tried to do total_interests = blog_post.interest_set.status.pending.count() but got AttributeError..'RelatedManager' object has no attribute 'status'

models.py

class BlogPost(models.Model):
 title                  = models.CharField(max_length=50, null=False, blank=False, unique=True)
 author                     = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
 slug                   = models.SlugField(blank=True, unique=True)

class Interest(models.Model):
   user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
   blog_post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)

class InterestInvite(models.Model):

   ACCEPT = "ACCEPT"
   DECLINE = "DECLINE"
   PENDING = "PENDING"
   STATUS_CHOICES = [
      (ACCEPT, "accept"),
      (DECLINE, "decline"),
      (PENDING, "pending"),

   ]

   interest = models.OneToOneField(Interest, on_delete=models.CASCADE, related_name="interest_invite")   
   status = models.CharField(max_length=25, choices=STATUS_CHOICES, default=PENDING)


views.py

class BlogPostMixin(object):
    model=BlogPost

class DetailBlogPostView(BlogPostMixin,DetailView):
    template_name = 'HomeFeed/detail_blog.html'

   def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        blog_post=self.get_object()
        total_interests = blog_post.interest_set.count()
        context['total_interests'] = total_interests
question from:https://stackoverflow.com/questions/65883626/how-to-query-only-the-pending-interest-and-not-interest-that-is-already-accepted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can query and filter to Interest and InterestInvite like the following:

Get all interests of a BlogPost object blog_post with status ACCEPTED like:

blog_post.interest_set.filter(interest_invite__status=InterestInvite.ACCEPT)

Or a count of all interests of a BlogPost object blog_post with status PENDING like:

blog_post.interest_set.filter(interest_invite__status=InterestInvite.PENDING).count()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...