how I get get only one column of my model using filter
ids = model1.objects.filter(key=value)
return model2.objects.filter(column__in=ids)
in above example first filter should return list of ids of model1 and in second example data will be return using in of 1st result ids
NOTE: model1 it's having number of field and one is id
CodePudding user response:
You can select only some columns using values_list
or values
:
ids = Model1.objects.filter(key=value).values_list('id', flat=True)
However, if you are going to filter on that, then this query is redundant at all (if I properly understand your schema).
Consider the following two models:
class Model1(models.Model):
name = models.CharField(max_length=50)
class Model2(models.Model):
m1_ref = models.ForeignKey(Model1, models.CASCADE)
Then two following queries are equivalent (but first is slower):
ids = Model1.objects.filter(name=value).values_list('pk', flat=True)
result = Model2.objects.filter(m1_ref__in=ids)
and
result = Model2.objects.filter(m1_ref__name=value)