0

I'm working on a simple keyword grouping tool.

Phrase represents keyword in search engine. SerpEntry represents link on site.

I'm looking for a way to group Phrases by SerpEntry urls.

Here are my models:

class Phrase(models.Model):
    text = models.CharField(max_length=1000, unique=True)

class SerpEntry(models.Model):
    phrase = models.ForeignKey(Phrase, related_name='serp_entry')
    position = models.PositiveIntegerField()
    url = models.TextField(max_length=2000)
    title = models.CharField(max_length=1000)
    snippet = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

Do you have any suggestions on how to do that?

example of result that I want to achieve:

urls = [
    'url1': [phrase1,phrase2,phrase3],
    'url2': [phrase2,phrase4,phrase5],
]
Alex T
  • 4,331
  • 3
  • 29
  • 47
  • Wouldn't be better to use [``ManyToMany``](https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/) relation instead of only ``ForeignKey``? One URL can have multiple phrases, so it would make sense. – Flaiming May 12 '16 at 08:22
  • SerpEntry is unique for each phrase, because urls can be on various position and change their position over time.. I've added snippet of full SerpEntry. BUT if you have solution of grouping with ManyToMany, you are welcome :) – Alex T May 12 '16 at 08:30

1 Answers1

0

not sure you can write a query that attaches a list of phrases to each entry object. You might have to do the grouping in python. A defaultdict(list) might come in handy. something like

urls = defaultdict(list)
for entry in grab_all_entries.filter().select_related('phrase'):
    urls[entry.url].append(phrase)
second
  • 28,029
  • 7
  • 75
  • 76