dragoon
dragoon

Reputation: 5743

Django select rows with duplicate field values for specific foreign key

again I would like to search for duplicates in my models, but now slightly different case.

Here are my models:

class Concept(models.Model):
    main_name = models.ForeignKey(Literal)
    ...
class Literal(models.Model):
    name = models.Charfield(...)
    concept = models.ForeignKey(Concept)
    ...

And now the task I'm trying to achieve: Select all literals that are NOT main_names, that have the same name for the same concept.

For example if I have literals:

[{id:1, name:'test', concept:1}, {id:2, name:'test', concept:1}]

and concepts:

[{id:1, main_name:1}]

Then in result I should get literal with the ID=2.

Upvotes: 1

Views: 631

Answers (2)

Gareth Rees
Gareth Rees

Reputation: 65854

It sounds to me as though you want to execute a SQL query something like this:

SELECT l1.* FROM myapp_literal AS l1,
                 myapp_literal AS l2
WHERE l1.id <> l2.id
  AND l1.name = l2.name
  AND l1.concept = l2.concept
  AND l1.id NOT IN (SELECT main_name FROM myapp_concept)
GROUP BY l1.id

Well, in cases where the query is too complex to easily express in Django's query language, you can always ask Django to do a raw SQL query—and this may be one of those cases.

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174624

If I understand your question you want:

  1. All Literal objects that are not ForeignKey'd to Concept.
  2. From that set, select those where the name and the concept is the same.

If so, I think this should work:

For the first part:

q = Literal.objects.exclude(pk__in=Concept.objects.values_list('id', flat=True))

EDIT:

Based on excellent feedback from Jan, I think for #2 you would need to use raw SQL.

Upvotes: 1

Related Questions