W
W
Wiki-fan2015-03-24 16:23:32
Django
Wiki-fan, 2015-03-24 16:23:32

How to search by tags?

Good afternoon.
There is this model:

class Picture(models.Model):
  ID = models.AutoField(primary_key=True)
        ...
  tags = models.BinaryField(max_length=1000)
  class Meta:
    ordering = ["ID"]

In tags I store set:
s = set([i for i in request.POST['tags'].split(' ')])
instance.tags = cPickle.dumps(s, protocol=cPickle.HIGHEST_PROTOCOL)
instance.save()

Checking if there is an element in the set seems to be O(log n), which is why I bother with pickle.
Question: is it ok? Is there a better way?
Question 2: how to organize the search now I present. But how to organize the delivery of results? Any
s = set([i for i in request.POST['search_query'].split(' ')])
picture_list = [for i in Picture.objects.all() if cPickle.loads(i.tags).issuperset(s)]
context_dict = {'pictures' : picture_list}

?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
un1t, 2015-03-24
@un1t

It's rough, you can't do that.
In general, there are many ways, but the easiest and correct one in your case is to use the ready-made library
https://github.com/alex/django-taggit

A
Anatoly Scherbakov, 2015-03-24
@Altaisoft

Another way, if you have PostgreSQL, is to use an Array field where you can store a list of strings (tags). Django ORM will allow you to search for these tags. Django-select2 is a handy widget that fits and works with the mentioned field.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question