Florent
Florent

Reputation: 1928

How to test if an instance has a subclass with ForeignKey pointing to it in Django?

I'm new with Django and I woul like to know if the instance of Market I'm working on has a t least on object of class Candle pointing to it. As you can see in my code the relation between Market and Candle has null=True so it's optional.

How can I perform this check?

models.py:

class Market(models.Model):
    pair = models.CharField(max_length=12, null=True)
    def __str__(self):
        return str(self.pair)

class Candle(models.Model):
    market = models.ForeignKey(Market,
                               on_delete=models.CASCADE,
                               related_name='market',
                               null= True
                               )
    dt = models.DateTimeField(unique=True)
    def __str__(self):
        return str(self.dt.strftime("%Y-%m-%d %H:%M:%S")) 

I tried many things but everytime it throw an error.

if instance.Candle().exists():
    ...
if Candle(market=instance).exists():
    ...

Thank you

Upvotes: 0

Views: 29

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

Since you are using related_nam=market you can use market atribute of Market instance to access related candles:

instance.market.exists() // instance - market instance

Or using Candle model:

Candle.objects.filter(market=instance).exists()

Upvotes: 1

Related Questions