I am trying to get a field value automatically pulled from different table. Below is my case: I have two tables: sales and returns. While entering a new return, when a "sales_id" is selected, want to show "sales_quantity" automatically populated, non-editable (and also if possible, want to constraint the "return_quantity" <= "sales_quantity").
class T_Sales(models.Model):
product = models.ForeignKey(P_Product)
sales_quantity = models.IntegerField()
def __unicode__(self):
return str(self.id)
class T_Return(models.Model):
sales_id = models.ForeignKey(T_Sales)
#sales_quantity = models.IntegerField(default=T_Sales.sales_quantity)
return_quantity = models.IntegerField()
def __unicode__(self):
return self.description
Creating property in your model will do the job.
sales_id
won't be null, so there will never be an issue when trying to get that value.Pros of that method:
T_Sales
object.Cons of that method:
select_related
in your queryset.If you wan't to create some validation, you can override model's
clean
method and do your comparsion here, if there is something wrong, you should throwValidationError
. Example:You can also assign error to
return_quantity
field, just pass dict in form'field_name': error
into validation error:You can't assign that error to
sales_quantity
.You can create separate field in
T_Return
model and copy value fromT_Sales
on save:Pros of that method:
T_Sales
only on (first) save.Cons of that method: - You're storing value in database twice - If value in
T_Sales
object will change, value inT_Return
won't be changed automatically (that can be fixed by simple trigger on save ofT_Sales
, but only inside django ORM)If you wan't to create some validation, you can override model's
clean
method and do your comparsion here, if there is something wrong, you should throwValidationError
. Example:You can also assign error to
return_quantity
or tosales_quantity
field, just pass dict in form'field_name': error
into validation error:Assigning that errot both to
return_quantity
andsales_quantity
will show that error twice.