Home > Software design >  Django filters two fields in different records with the same value
Django filters two fields in different records with the same value

Time:01-17

In Django, I have a large amount of data(real data is about tens of thousands). I want to find all records with the same amount of income and expenditure. What should I do? Mysql:

id income expenses
1 0.00 50.00
2 0.00 43.00
3 50.00 0.00
4 50.00 0.00
5 29.00 0.00
6 23.00 0.00
7 0.00 23.00
8 0.00 5.00
9 0.00 12.00

I want to filter out data 13467. All expenses and income amounts have the same data (excluding the amount is 0.00)

id income expenses
1 0.00 50.00
3 50.00 0.00
4 50.00 0.00
6 23.00 0.00
7 0.00 23.00

CodePudding user response:

you can do this:

from django.db.models import F

data = Model.objects.filter(income_field=F("expenses_field_name")).exclude(income_field=0)

same question with Datetime Field. Answer

CodePudding user response:

from itertools import chain

list_id = []
for i in Model.objects.filter(income__gt=0):
    ids = Model.objects.filter(expenses=i.income).values_list("id",flat=True)
    list_id.append(ids)

#flatten the list of lists
list_id = list(set(chain.from_iterable(list_id)))

I want to implement this function, but my data volume is too large, and I don't want to use the for loop to implement it. I want to know if there is a simpler way.

  • Related