简体   繁体   中英

Create a queryset to compare two models

I'm just new using Django. I just created my models and migrate information to my sqlite3 database using the .cvs import module. This are my modules:

class Backlog(models.Model):
    sales_order = models.CharField(max_length=30)
    po_number = models.CharField(max_length=30)
    order_number = models.IntegerField(blank=True)
    line_number = models.IntegerField(blank=True)
    ship_Set = models.IntegerField(blank=True)
    product_id = models.CharField(max_length=30)
    ordered_quantity = models.IntegerField(blank=True)

class Material(models.Model):
    product_id = models.CharField(max_length=50)
    tan_id = models.CharField(max_length=50)

Now that I have the information inside my tables I want to do the following:

  • Find if product_id from Backlog is in Material 's model, once it finds it verify the first two digits from the tan_id . If is 74 classify as '1' , if is 800 classify as '3' else set as '2' . ( tan_id format commonly are 74-102345-03 , 800-120394-03 )

My two questions are: How to do that and if I have to create a new column to add the information from every product_id .

Ok well given your current models, here is a possible solution to the problem you are having:

for backlog in Backlog.objects.all():
    try:
        material = Material.objects.get(product_id = backlog.product_id)
        if material.tan_id[0:2] == '74':
            # Classify as 1
        elif material.tan_id[0:2] == '80':
            # Classify as 3
        else:
            # Classify as 2
    except Material.DoesNotExist:
        print("This material is not in backlog")
        continue

This code should loop over every instance of Backlog you have in your database and then try to find the associated Material. In the event it doesn't find a Material (in your case there is no backlog), objects.get() raises an exception that it doesn't exist, we print it's not there and continue on with the loop. If it is we classify it as you specified. Might require a slight bit of tweaking but it should give you the bones of what you want to fix this problem. Let me know if it doesn't.

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