Can django model inject classes?

I want to have a django model like this:

class Model(models.Model):
 string = models.CharField()
 class ContactDetails:
  phone = models.IntegerField()

      

Is it possible? I tried searching the web but didn't seem to answer my question.

This would mean that I would have access:

Model().ContactDetails.phone

      

works like this :)

Joe

+2


a source to share


1 answer


It can have built-in classes (common case class Meta

), but any members are models.*Field

ignored. It doesn't make sense in SQL.

What you want is many-to-one:

class Thing(models.Model): # Don't name this class 'Model'!
    name = models.CharField(max_length=100)

class ContactDetails:
    parent = models.ForeignKey(Thing, related_name="contactDetails")
    phone = models.IntegerField()

      



Then to access:

thing = Thing();
# ... set up thing ...
thing.save()
contact1 = ContactDetails(parent=thing)
# ... set up contact1 ...
contact1.save()
contact2 = ContactDetails(parent=thing)
# ... set up contact2 ...
contact2.save()
# ...
thing.contactDetails.all()
# returns a list with contact1 and contact2

      

or something else.

+1


a source







All Articles