Alex Burov
Alex Burov

Reputation: 11

Django add field to query set

Hi i have 3 models in my django projects, when user send request i have his dealer_id i need return query set with info about material from Material table and for each row add discount_percent from last model where dealer_id = current dealer_id and row id. Please help me if you have answer.

models

class Material(models.Model):
    id = models.AutoField(primary_key=True)
    color = models.IntegerField() 
    name = models.CharField(max_length=100)
    material_width = models.IntegerField()
    price = models.BigIntegerField(default=0)  

class Dealer(models.Model):
    id = models.AutoField(primary_key=True)
    dealer_name = models.CharField(max_length=100)
    dealer_phone = models.CharField(max_length=13, unique=True)
    dealer_email = models.CharField(max_length=150, null=False, unique=True)
    dealer_firm_name = models.CharField(max_length=100, null=True)
    dealer_address = models.CharField(max_length=100, null=True)
    dealer_unp = models.CharField(max_length=9, null=True)
    dealer_amount = models.FloatField(default=0.0)
    user_id = models.BigIntegerField(unique=True) 

class MaterialDealerPrice(models.Model):
    id = models.AutoField(primary_key=True)
    dealer_id = models.BigIntegerField(null=False)
    material_id = models.BigIntegerField(null=False)
    discount = models.FloatField(null=True, default=0.0)

Upvotes: 1

Views: 101

Answers (2)

rajkris
rajkris

Reputation: 1793

Annotate can be used for this purpose. https://docs.djangoproject.com/en/1.11/topics/db/aggregation/

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

This looks like a set of models that were automatically created by running inspectdb. You should always treat that output as a first draft; there is a lot that needs to be done manually to tidy it up.

Firstly, your MaterialDealerPrice model needs to have foreign keys to Dealer and Material:

class MaterialDealerPrice(models.Model):
    dealer = models.ForeignKey('Dealer', null=False)
    material = models.ForeignKey('Material', null=False)
    discount = models.FloatField(null=True, default=0.0)

Secondly, you should recognise that this model is in fact the through table of a many-to-many relationship.

class Material(models.Model):
    ...
    dealers = models.ManyToManyField('Dealer', through='MaterialDealerPrice')

Now, you should be able to follow these relationships in your query. Unfortunately your question is not clear enough to know what you actually want to do; you should give an example of the desired output.

Upvotes: 0

Related Questions