简体   繁体   中英

How can I compare two Django QuerySets and return QuerySet with replacement of the same values from second in first?

My env is Django 2.0.2 and Python 3.6.1 .

How can I compare two Django QuerySets and return QuerySet with replacement of the same values from second in first?

For example, I have QuerySets:

>>> qs_local = PriceLocal.objects.filter(user_id=request.user.id)
>>> print(qs_local)
[{ 'user_id': 1, 'product_id': 1, 'price': 100 }] # one record

>>> qs_world = PriceWorld.objects.all()
>>> print(qs_world)
[{ 'product_id': 1, 'price': 300 }, { 'product_id': 2, 'price': 500 }, ... ] # many records

I want to compare this Django QuerySets and return QuerySet, like this:

[{ 'product_id': 1, 'price': 100 }, { 'product_id': 2, 'price': 500 }, ...]

At this point, we are replacing the same records (with 'product_id': 1 ) from second to first QuerySet.

EDIT:

My models:

class PriceWorld(models.Model):

    product_id = models.PositiveSmallIntegerField()
    price = models.PositiveSmallIntegerField()

class PriceLocal(models.Model):

    user_id = models.ForeignKey(User, on_delete=models.CASCADE)
    product_id = models.ForeignKey(PriceWorld, on_delete=models.CASCADE)
    price = models.PositiveSmallIntegerField()

It's not entirely clear what you are asking, but you seem to want the elements from PriceWorld that match the product_ids of those elements in PriceLocal related to a specific user ID. So:

PriceWorld.objects.filter(product_id__in=PriceLocal.objects.filter(user_id=request.user.id))

which will be executed as a subquery.

Note, your original query can be written as just request.user.pricelocal_set.all() , assuming you haven't changed the related_name, so you can do:

PriceWorld.objects.filter(product_id__in=request.user.pricelocal_set.all())

which is exactly the same query/subquery but a bit more readable.

Don't know about queryset:

but required output can achieve by using:

for qs in qs_world:
    if qs['product_id']==qs_local[0]['product_id']:
        qs['price']=qs_local[0]['price']
    else:
        print "hii" 
print qs_world

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM