I have the following models:
class Article(models.Model):
manufacturer_sku = models.TextField(db_index = True, unique=True)
class ExternalSource(models.Model):
name = models.CharField(max_length=128, unique=True)
class ExternalConnections(models.Model):
external_source = models.ForeignKey(ExternalSource, on_delete=models.CASCADE)
article = models.ForeignKey(Article, on_delete=models.CASCADE)
value = models.TextField()
I need to get the article referenced by an entry in ExternalConnectons with value = itscope_id and referencing an ExternalSource entry with name = ‘itscope_id’.
Currently i am first filtering for the ExternalConnection and accessing the article via the attribute like this:
external_connection = await ExternalConnections.objects.filter(value = itscope_id, external_source__name = 'itscope_id').afirst()
if external_connection == None:
raise ArticleNotFound(sku, itscope_id)
def sync_externalconnection_to_article():
self._article = external_connection.article
await sync_to_async(sync_externalconnection_to_article)()
My initial thought was that this could be condensed into one query like this:
article =
Article.objects.filter(externalconnections__externalsource__name="itscope_id", externalconnections__value=itscope_id).first()
But this results in an error:
Unsupported lookup 'externalsource' for ManyToOneRel or join on the field not permitted.
Can the sql query below be perfomed using Django ORM or do i have to resort to raw SQL?
SELECT articles_article.* FROM articles_article
INNER JOIN articles_externalconnections
ON articles_article.id=articles_externalconnections.article_id
INNER JOIN articles_externalsource
ON articles_externalsource.id=articles_externalconnections.external_source_id
WHERE articles_externalsource.name='itscope_id' AND articles_externalconnections.value='17814839000'
Edit: Reduced models to relevant fields
Edit2: Typo
Edit3: SQL