1👍
✅
If I were you, I would change the structure so that Address could be an inline. In the models.py:
class Customer(models.Model):
name = models.CharField(max_length=64)
class Address(models.Model):
costumer = models.OneToOneField(Costumer)
address_line1 = models.CharField(max_length=64)
address_line2 = models.CharField(max_length=64)
address_line3 = models.CharField(max_length=64)
post_code = models.CharField(max_length=5)
And then, in the admin.py:
class AddressInline(admin.StackedInline):
model = Address
extra = 1
max_num = 1
class CostumerAdmin(admin.ModelAdmin):
inlines = [AddressInline]
admin.site.register(Costumer, CostumerAdmin)
👤bcap
0👍
for field in YourModelClass._meta.get_fields():
# iterate through main model's fields
if isinstance(field, OneToOneField):
# if the field is an OneToOneField
for field2 in YourModelClass._meta.get_field(field.name).related_model._meta.get_fields():
# iterate through the OneToOneField's fields
fieldname = field2.name
fieldvalue = field2.value_from_object(getattr(instance, field.name))
# getattr simulates instance.`field.name`
else:
fieldname = field.name
fieldvalue = field.value_from_object(instance)
where YourModelClass is the model that contains more OneToOneField objects and/or other basic models. In the example above, it is Address, and instance is the instance of the model.
Please notice you don’t need the instance to get the field names, but you need it if you want to get the field value.
I use this code to convert an instance of a model into a context dictionary for dynamic settings, i’m not sure it’s the best solution.
Source:stackexchange.com