0

I want to implement something like the pattern which introduced in this answer. For example I have four models like this:

class Protperty(models.Model):
    property_type = models.CharField(choices=TYPE_CHOICES, default='float', max_length=100)
    property_name = models.CharField(max_length=100)

class FloatProperty(models.Model):
    property_id = models.ForeignKey(Property, related_name='value')
    value = models.FloatField(default=0.0)

class IntProperty(models.Model):
    property_id = models.ForeignKey(Property, related_name='value')
    value = models.IntField(default=0)

class StringProperty(models.Model):
    property_id = models.ForeignKey(Property, related_name='value')
    value = models.CharField(max_lenght=100, blank=True, default='')

After defining these classes, I do not know how I must implement serializer or view classes. For example for writing serializer I want to put a field value, which must be set depend of type of object currently is serialized or deserialilzed(property_type defines it). I am new to django and rest framework too, please give me some suggestions for implementing such models and serializers.

Edit:

In general I want to construct some models that using them I able to store run time defining property with different values and able to query them further. For example I have a store and it has different goods which each one has specific property and I want to query them using a specific property.

Community
  • 1
  • 1
motam
  • 677
  • 1
  • 6
  • 24
  • 1
    Maybe something like a json field would fit better, so you could store properties however you like without a strict structure, and then search json at db level (django has support for json fields if using postgres). – serg Apr 15 '16 at 07:16
  • I heard about that but I have not any experience in working with postgres. Do you think that using the ordinary sql model in django rest framework I will be able to implement this? – motam Apr 15 '16 at 07:33
  • If your database is postgres then yes it's fully supported by django (for django rest you would need to write some filters yourself) https://docs.djangoproject.com/es/1.9/ref/contrib/postgres/fields/#querying-jsonfield Before going all in you could try creating a test table with json field and play with it, see if you can store all required data and make sql queries you need. – serg Apr 15 '16 at 16:16
  • It seems very helpful, I am currently working on this approach, It must be the exact thing that I were looking for. – motam Apr 15 '16 at 16:46

0 Answers0