5

Is it possible to use something similar to the inline relational items from the Django admin to represent embedded models in a ListField?

For Example, I've got the following models:

class CartEntry(model.Model):
    product_name=model.CharField( max_length=20 )
    quantity = model.IntegerField()

class Cart(model.Model):
    line_items = ListField(EmbeddedModelField('CartEntry'))

I've tried using the standard inlining, but I know it's not right:

class CartEntryInline( admin.StackedInline ):
    model=CartEntry

class CartAdmin(admin.ModelAdmin)
    inlines=[CartEntryInline]

But obviously that doesn't work, since there's no foreign key relation. Is there any way to do this in django-nonrel?

Community
  • 1
  • 1
Adam Ness
  • 6,224
  • 4
  • 27
  • 39

1 Answers1

0

This is not so easy to do out of the box. You will need to manage ListField and EmbeddedModelField type fields in Django's admin module and do some hacking to get it done. You'll have to implement two parts:

Use EmbeddedModelField in Django's admin

You need to define a class that handles EmbeddedModelField objects to make it work with Django's admin. Here is a link where you can find great sample codes. Below are just code blocks for demonstration:

Add this class into your models.py file and use EmbedOverrideField instead of EmbeddedModelField in Cart model:

class EmbedOverrideField(EmbeddedModelField):
    def formfield(self, **kwargs):
        return models.Field.formfield(self, ObjectListField, **kwargs)

Implement a class in forms.py that has two methods:

class ObjectListField(forms.CharField):
    def prepare_value(self, value):
        pass # you should actually implement this method

    def to_python(self, value):
        pass # Implement this method as well

Use ListFields in Django's admin

You also need to define a class that handles ListField objects to make it work with Django's admin. Here is a link where you can find great sample codes. Below are just code blocks for demonstration:

Add this class into your models.py file and ItemsField instead of ListField in Cart model:

class ItemsField(ListField):
    def formfield(self, **kwargs):
        return models.Field.formfield(self, StringListField, **kwargs)

Implement a class in forms.py that has two methods:

class StringListField(forms.CharField):
    def prepare_value(self, value):
        pass # you should actually implement this method

    def to_python(self, value):
        pass # Implement this method as well
Saeed
  • 661
  • 6
  • 12