Friday, November 2, 2018

Re: Left outer join rather than subquery.

I'm going to answer myself in case anyone else looks for an answer to this.   In Django<2.x, the Subquery method I'm using is the best available.

In Django>=2, I can use the FilteredRelation with my annotation instead:

https://docs.djangoproject.com/en/2.1/ref/models/querysets/#django.db.models.FilteredRelation

The uniqueness constraint is actually already there in my actual model, and Django supports that through unique_together = ('journal', 'issn_type').

On Tuesday, October 30, 2018 at 2:05:58 PM UTC-4, Dan Davis wrote:

Suppose you have a setup like this:

     class Journal(models.Model):
          title = models.CharField(max_length=200)


     issn_type_choices = (
         ('E', 'Electronic'),
         ('P', 'Print'),
     }

     class Issn(models.Model):
          ELECTRONIC='E'
          PRINT='P'

          journal = models.ForeignKey(Journal)
          issn_type = models.CharField(max_length=1)
          issn = models.CharField(max_length=10)


I can express annotations to assure I get botha  Physical and Print ISSN:

issn_p=Issn.objects.filter(issn_type='E', journal_id=OuterRef('id'))
issn_e=Issn.objects.filter(issn_type='P', journal_id=OuterRef('id'))
queryset = Journal.objects.annotate(issn_print=Subquery(issn_p), issn_electronic=Subquery(issn_e)).filter(issn_print__isnull=False, issn_electronic__isnull=False)

However, is there anyway for me to express two OneToOneField relationships from Issn to Journal to make sure a constraint is added at the database level and get easier querysets?


Thanks,

-Dan

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bc06ee4d-e159-4ea1-b44b-f8099b567581%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment