SoWa
SoWa

Reputation: 314

Django filtering from other model

For example I have two models:

class Symbol(models.Model):
    rowID = models.CharField(max_length=64, primary_key=true)

class SymbolProperties(models.Model):
    symbol = models.ForeignKey(Symbol, to_field='rowID', db_column='symbol')
    some_value = models.IntegerField(default=0)

And I want to filter Symbol objects with some_value field, but model Symbol have no relation to SymbolProperties.
Can I do it without creating foreign key in Symbol model?

Upvotes: 2

Views: 6142

Answers (2)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 49092

Yes. When you declare a ForeignKey on one model, a reverse relationship is added to the other one (see the documentation).

You can access the related field as an attribute (symbol.symbolproperties_set, or whatever name you define using the related_name keyword argument in the model field definition) or reference it in a lookup:

Symbol.objects.filter(symbolproperties__some_value=5)

(Add distinct() to ensure that the result only contains unique instances of Symbol.)

Upvotes: 6

Brandon Taylor
Brandon Taylor

Reputation: 34593

You can get to objects from either side of a relationship. See: https://docs.djangoproject.com/en/1.5/topics/db/queries/#following-relationships-backward for more information.

Try:

symbols = SymbolProperties.objects.filter(some_value=the_value).only('symbol')

This may result in duplicate symbol instances in the returned QuerySet. To get rid of those, you'd need to create a set of the results.

Upvotes: 2

Related Questions