Home > Software design >  Filter Django Queryset_A with Queryset_B based on a specifict one property with the same value
Filter Django Queryset_A with Queryset_B based on a specifict one property with the same value

Time:08-26

  1. Filter Model_A with Model_B
  2. Return Items of Model_A
class Model_A(models.Model):
    name = models.CharField()
    age = models.CharField()

class Model_B(models.Model):
    name = models.CharField()
    location = models.CharField()

def some_filter_function():
    return [list of Model_A items based on Model_B.name]

CodePudding user response:

considering you can't change the Model to use foreignkey, you can try something like this:

    my_items = []
    names = Model_b.objects.all()
    for name in names:
        name_b = name.name
        model_a = Model_a.objects.filter(name = name)
           for item in model_a:
               my_items.append(item)   

CodePudding user response:

I agree with @William Van Onsam.

If you define your Model_A like

class Model_B(models.Model):
    name = models.CharField()
    location = models.CharField()

class Model_A(models.Model):
    name = models.CharField()
    age = models.CharField()
    b = models.ForeignKey(Model_B, on_delete=models.CASCADE)
    # NOTE you need to declare Model_B prior to Model_A, 
    # and then you can use Model_B as a parameter here.

Then you can do

def some_filter_function():
    b = get_model_b()
    return Model_A.objects.filter(name=b.name)

in your view function.

  • Related