简体   繁体   中英

Search query on more than one model in Django

I have two models:

class City(models.Model):
    name = models.CharField(max_length=50, verbose_name='Qyteti')
    slug = models.SlugField(unique=True) 

class Business(models.Model):
    name = models.CharField(max_length=120, verbose_name='emri')
    slug = models.SlugField(unique=True)
    city = models.OneToOneField(City, verbose_name='qyteti')
    created = models.DateTimeField(auto_now_add=True, verbose_name='krijuar')
    categories = models.ForeignKey(Category, related_name='businesses', verbose_name='kategoria')
    user = models.ForeignKey(User, related_name='user_businesses', verbose_name='autori')
    geom = gis_models.PointField(u"longitude/latitude", geography=True, blank=True, null=True)

I want to create a serach like yelp.com 在此处输入图片说明

I want people to search in three different ways.

  1. One type of business in all cities.
  2. All type of businesses in one city.
  3. One type of business in one city.

I've tried chain from itertools, but no results so far.

I'd like to do just a simple search for now, not with external search engines.

Anyone's help is appreciated.

You need to do the following:
1) Change in your model:

class Business(models.Model):
    city = models.ForeignKey(City, verbose_name='qyteti', related_name='businesses')

2) Queries:

1) one_type = Business.objects.filter(name = "some_business_type").select_related('city')
one_type.city.name

2) one_city_all_business = City.objects.filter(name = "London").prefetch_related('businesses')
one_city_all_business.businesses.all() - here u get a list of all businesses for London

3) one_type_one_city = City.objects.filter(name = "London").filter(businesses__name = "some_business_type").prefetch_related('businesses')

The only problem here - you need to decide how user will select what query to run, I mean how will you define what user wants to search for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM