gamer
gamer

Reputation: 613

Merge two Different fields result django Query

I have a model from which I want to get data in a same object(JSON) I have this model

class Suggestion(models.Model):
   city = models.CharField(max_length=250 , null=True , blank=True)
   name = models.CharField(max_length=250 , null=True , blank=True)

Now I will query like this

           name = Suggestion.objects.filter(name__icontains=search)
           city = Suggestion.objects.filter(city__icontains=search)
           Name=nameSeilizerr(activities,many=True)
           serializer=CitySeilizer(city,many=True)

In serializer I will send only name in Nameserializer and city in city Serilizer.

Main Concept is I want to suggestion to user either its Name or city name in field. Any help would be highly appreciated.

Upvotes: 1

Views: 225

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

You can make use of Q objects to search for Suggestions where the name or the city matches (or both):

from django.db.models import Q

suggestions = Suggestion.objects.filter(
    Q(name__icontains=search) |
    Q(city__icontains=search)
)
serializer=CitySerializer(suggestions, many=True)

Upvotes: 2

Related Questions