You can use Intermediate Models: https://docs.djangoproject.com/en/1.6/topics/db/models/#intermediary-manytomany
Django: Adding a ManyToMany field that can have alternated values posted to it
-
07-10-2022 - |
Question
I am attempting to create a model where an unspecified number of characteristics can be added to a model field with each characteristic having a value assigned to it that is user defined.
My attempt:
class Characteristic(models.Model):
name = models.CharField(max_length = 50)
value = models.FloatField()
class Object(models.Model):
name = models.CharField(max_length = 50)
chars_added = models.ManyToManyField(Characteristic, null=True, blank=True)
This allows me to add any number of characteristics but it does not let me assign a number that is unique to the Object class that is created. I realize that creating a separate Model class may not be the best approach but it is as close to what I need to create.
ANSWER FOUND: https://docs.djangoproject.com/en/1.6/topics/db/models/#intermediary-manytomany
class Characteristic(models.Model):
name = models.CharField(max_length = 50)
class Object(models.Model):
name = models.CharField(max_length = 50)
chars_added = models.ManyToManyField(Characteristic,through= 'Value')
class Value(models.Model):
characteristic = models.ForeignKey(Characteristic)
object = models.ForeignKey(Object)
value = models.FloatField()
I believe I have been clear, but please feel free to ask any questions you may have in order to clarify the question.
La solution
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow