how can we query foreign key and get results of objects which are connected to foreign key

142
February 21, 2018, at 1:48 PM

How can I can use managers to query my foreign key and then retrieve objects that are connected to foreign key?

Here is my models.py:

from django.db import models
# Create your models here.
class BookManager(models.Manager):
    def title_count(self,keyword):
        return self.filter(title__icontains=keyword).count()
class CategoryManager(models.Manager):
    def category_count(self):
        return self.filter(category__icontains=python).count()
class Category(models.Model):
    title=models.CharField(max_length=20)
    def __str__(self):
        return self.title
class Enquiry(models.Model):
    title=models.CharField(max_length=200)
    category=models.ForeignKey(Category ,default=False,blank=False)
    detail=models.TextField()
    objects = BookManager()
    objects=CategoryManager()
    # tags=models.ChoiceField()
    def __str__(self):
        return self.title

I tried to use category manager but it gave me a strange error. I just want to know how exactly we can get the objects that are connected with category foriegn-key and show them as list to the users.

Answer 1

You can combine both the title_count and category_count methods under one Manager. When filtering through a ForeignKey, your field lookup needs to specify the name of the field you're trying to filter on, else it will assume you're querying the ID field. So instead of category__icontains, you would do category__title__icontains.

Another note, in newer versions of Django, you are required to specify the on_delete parameter when defining a ForeignKey.

This is a working example of what I think you're trying to accomplish.

class BookManager(models.Manager):
    def title_count(self, keyword):
        return self.filter(title__icontains=keyword).count()
    def category_count(self, keyword):
        return self.filter(category__title__icontains=keyword).count()

class Category(models.Model):
    title = models.CharField(max_length=20)
    def __str__(self):
        return self.title

class Enquiry(models.Model):
    title = models.CharField(max_length=200)
    category = models.ForeignKey(Category,
                                 default=False,
                                 blank=False,
                                 on_delete=models.CASCADE)
    detail = models.TextField()
    books = BookManager()
    # tags=models.ChoiceField()
    def __str__(self):
        return self.title

Here's how you would use it:

Enquiry.books.category_count('python')
Enquiry.books.title_count('test')
READ ALSO
Python: Converting degrees to radians - Not working

Python: Converting degrees to radians - Not working

I have tried doing the following in Python with numpy but my answer is not coming out to the value I wantI want cos(30) = 0

197
Showing a progress bar on front-end until a processing function finish executing in back-end in flask web application

Showing a progress bar on front-end until a processing function finish executing in back-end in flask web application

I'm developing an online GNSS post processing portal for my office websiteIn the application user have to enter 2 files

111
Use of Relative cardinality in adjacency relation for Fuzzy Connectedness

Use of Relative cardinality in adjacency relation for Fuzzy Connectedness

I am using Fuzzy Connectedness technique for image segmentation and it has fuzzy adjacency function with f(c,d)=||c-d||<=1 where c and d are pixel intensity,as I only know || is relative cardinalityso please anyone tell me what above function is concluding...

141
Python: How to use Ramer Douglas Peucker (RDP) in Python?

Python: How to use Ramer Douglas Peucker (RDP) in Python?

I have a source code of RamerDouglasPeucker, and array pointsand want to draw a line between them but dont understand why its not workin on me? Anybody can help to fix it?

281