vendredi 31 juillet 2015

Django unique_together but only for filtering

Is there a way to filter a django model, where two fields are unique together?

For example, I have this model:

class Sequence(models.Model):
    id       = models.CharField(max_length=25, primary_key=True)
    taxonomy = models.CharField(max_length=25)
    sequence = models.TextField()

There can be multiple Sequence objects that have the same the sequence and taxonomy. I want to have a unique subset of Sequence objects where no taxonomy has multiple sequences that are identical, and only pick one object if there are multiple.

So far I have tried iterating over the results:

def unique(query_set):
    used_taxa = {}
    for seq in query_set.all():
        if not seq.sequence in used_taxa:
            used_taxa[seq.sequence] = [seq.taxonomy]
            yield seq
        elif seq.sequence in used_taxa and not seq.taxonomy in used_taxa[seq.sequence]:
            used_taxa[seq.sequence].append(seq.taxonomy)
            yield seq
        else:
            pass

This gets me the correct result, but I need the overall count becuase I am doing pagination later on.

This also gets me closer, but I don't have access to the full Sequence object after values has been called:

result = Sequence.objects.values("sequence", "taxonomy").annotate(id=Max("id"))

If someone can point me in the right direction, I would really appreciate it! Thanks.

Aucun commentaire:

Enregistrer un commentaire