I have an application that has a Company, and this company can have 0 or multiple addresses. Companies are not the only 'models' that could have addresses. To achieve this, I use ContentTypes.
models.py
class Company(models.Model):
''' models a company in the system. '''
number = models.CharField(_('Number'), unique=True, max_length=20)
name = models.CharField(_('Name'), max_length=100)
active = models.BooleanField(_('Active'), default=True)
def _get_addresses(self):
'''
'''
contentType = ContentType.objects.get(
model=self.__class__.__name__.lower()
)
try:
addresses = Address.objects.get(
actor_type=contentType, actor_id=self.id
)
except Address.DoesNotExist:
addresses = []
return addresses
addresses = property(_get_addresses)
class Address(Auditable):
''' models an address '''
actor_type = models.ForeignKey(ContentType)
actor_id = models.PositiveIntegerField()
actor_object = fields.GenericForeignKey('actor_type', 'actor_id')
_type = models.CharField(
_('Address Type'),
max_length=10,
choices=sorted(TYPES.items())
)
active = models.BooleanField(default=True)
address1 = models.CharField(_('Address 1'), max_length=50)
address2 = models.CharField(
_('Address 2'),
max_length=50,
...
This way, I could also have a Profile model and I could link multiple addresses to a Profile. However, my problem comes when I tried to implement the Serializers.
Serializers.py
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = (
'_type',
'address1',
'address2',
'address3',
'country',
'state',
'city'
)
class CompanySerializer(serializers.ModelSerializer):
addresses = AddressSerializer(required=False, many=True)
class Meta:
model = Company
fields = (
'number',
'name',
'addresses'
)
This implementation gives me this error. It says that it cannot iterate through Address model (which makes sense), but I'm not sure how to make my addresses iterable.
I would need to perform CRUD operations not only on the Company, but also on the nested Addresses.
Any suggestions/ideas on how to go about this?
Company
toAddress
(aside from theaddresses
property; just added it to the models.py), but you can get a relationship fromAddress
toCompany
, or to any other model. – m4rk4l