Reputation: 29
I'm trying to figure out how to allow for a model to take only certain values. But I can't use IntegerField with choices option because it's product database with couple thousand products. To be more precise- I'm trying to create app which manages product orders. For now my models are:
class Order(models.Model):
timestamp = models.DateField(auto_now_add=True)
komentarz = models.CharField(max_length=150, unique=False)
class Product(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
r = models.CharField(max_length=50, unique=False)
s = models.CharField(max_length=50, unique=False)
p = models.CharField(max_length=50, unique=False)
I created another app with product database, it contains around 3000 records.
class ProductBase(models.Model):
r = models.CharField(max_length=50, unique=False)
s = models.CharField(max_length=50, unique=False)
p = models.CharField(max_length=50, unique=False)
Basically I want to allow Product model to take values inside database made thanks to ProductBase model. Any idea what should I use?
EDIT: To make it more clear:
R S P
Name 1 Parameter S Parameter P
Name 2 Parameter S Parameter P
Name 3 Parameter S Parameter P
This is ProductBase database. I want to allow Product to take only one of these three values. (in reality it's 3000)
Upvotes: 0
Views: 997
Reputation: 201
To allow only a specific set of values in Product model, base on some 'condition', I would just check this condition in the view function before saving a new Product object to the database.
So if you get r, s, p
to create new Product, let say from a form, then check whether the condition is met, then you save new Product object to db or not.
Let just say that set of r, s, p values must be exactly that same in Product and ProductBase. Example could be sth like that:
# receive data from the form
r_value = form.clean_data.get("r")
s_value = form.clean_data.get("s")
p_value = form.clean_data.get("p")
# Your condition
check_db = ProductBase.object.filter(
s=s_value).filter(r=r_value).filter(p=p_value).exists()
if check_db:
# create new product
new_product = Product.object.create( #here goes values r, s, p )
new_product.save()
else:
# soma kind of feedback to user
The condition could be whatever you want, just change the logic.
Upvotes: 1