On Wed, 2009-04-08 at 08:03 -0700, cfiles wrote:
> Is it possible to force a base model to have a sub model? Consider the
> following model...
> 
> class Account(models.Model):
>     user        = models.ForeignKey('auth.User')
>     name        = models.CharField(max_length=100)
>     description = models.CharField(max_length=35, blank=True)
>     date_added  = models.DateField(auto_now_add=True, blank=True)
> 
> class CheckingAccount(Account):
>     routing_number = models.IntegerField(max_length=9)
>     account_number = models.IntegerField(max_length=15)
> 
> class CreditCardAccount(Account):
>     type   = models.CharField(max_length=1)
>     number = models.IntegerField(max_length=16)
>     exp    = models.CharField(max_length=5)
> 
> class Payment(models.Model):
>     account     = models.ForeignKey(Account)
>     date_billed = models.DateField()
>     date_paid   = models.DateField(blank=True)
>     amount      = models.DecimalField(max_digits=10, decimal_places=2)
> 
> I want to require that the Payment model have an Account. That works
> fine, but I want that account to either be a CreditCardAccount or
> CheckingAccount. Right now in the admin interface when I view the
> Payment form I get the opportunity to add an Account. That is fine but
> it means nothing without a relationship with CreditCardAccount or
> CheckingAccount.

So you don't actually want an Account link. You want to add a link to a
CheckingAccount or CreditCardAccount. There are two approaches here:

(1) Reflect the requirement in the data modelling. Particularly useful
if it's going to be a firm requirement, always. The way to provide
relations between a model and multiple other models is to use the
GenericRelation field, which tracks the content type along with the pk
value for the related object.

(2) Override the admin change form so that the appropriate account type
information is also collected. You'll need to provide a custom ModelForm
to the admin, with some extra fields and override the save_form() and
save_model() methods on the ModelAdmin class. Might require a little bit
of reading of the code, but those are the three key points and it's not
too hard to do some admin customisations along those lines. Thinking
about it for a few more seconds... maybe you actually need to provide a
custom formset in the ModelAdmin class. Will depend on your UI flow and
how general you want to make your customisations, I guess.

Regards,
Malcolm



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to