S
S
sidsukana2018-07-07 08:33:54
Django
sidsukana, 2018-07-07 08:33:54

How to make an additional selection condition for a foreign key field in a django model?

There are 2 models:

class A(models.Model):
    id = models.PositiveIntegerField(default=0, primary_key=True)
    version = models.PositiveIntegerField(default=0)
    value = models.PositiveIntegerField(default=0)
    
class B(models.Model):
    id = models.PositiveIntegerField(default=0, primary_key=True)
    version = models.PositiveIntegerField(default=0)
    a_value = models.ForeignKey(A, on_delete=models.DO_NOTHING)

How to make it so that when accessing the a_value field in model B , the version field is taken into account ? Roughly speaking, instead
A.objects.get(pk=self.a_value)
of doing
A.objects.get(pk=self.a_value, version=self.version)

It occurred to me to use property, but maybe there is a more elegant way?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vadim Shatalov, 2018-07-12
@netpastor

In order not to constantly register, create a custom queryset manager and make a method there in which the version field will be taken into account

T
Tim, 2018-07-21
@darqsat

The ORM has a select_related() method Explore
:
https://docs.djangoproject.com/en/2.0/ref/models/q...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question