Ben
Ben

Reputation: 7124

DRY django models, creating a list of objects

I have some model for a user profile and I want to be able to store several types of information but with some deferences (like a home or work phone number) but I don't want to use a ForeignKey relation ...how would I do that?

something like:

class Profile(models.Model):
    phone = ? list of some kind ?

    class Phone(???):
        TYPE_CHOICES = (
                ('H', 'Home'),
                ('W', 'Work'),
                ('F', 'Fax'),
                )
        type = models.CharField(max_length = 1, choices = TYPE_CHOICES) 
        number = models.CharField(max_length = 16)
        private = models.BooleanField()

Thank you!

Edit: I didn't want to use a foreign key just because I originally wanted all information relating to a user to show up on the profile admin page. but... meh... that's not too critical

Upvotes: 2

Views: 235

Answers (1)

marianobianchi
marianobianchi

Reputation: 8488

Why don't you want to use a foreign key? If you want to have multiple phone numbers, that's the way you need/must do it.

It's easy to work with Django and foreign keys, and you can easily add an inline model formset into the admin page to create/edit a user profile with plenty of phone numbers.

Your models should look like this:

class Profile(models.Model):
    name = models.CharField(max_length=40, verbose_name="User name")

class Phone(models.Model):

    TYPE_CHOICES = (
        ('H', 'Home'),
        ('W', 'Work'),
        ('F', 'Fax'),
    )

    profile = models.ForeignKey(Profile)
    type = models.CharField(max_length = 1, choices = TYPE_CHOICES) 
    number = models.CharField(max_length = 16)
    private = models.BooleanField()

Then, you could use something like this to easily add/edit multiple phone numbers per profile in one admin page.

In your example, you should do something like this (inside admin.py file, in your django app):

class PhoneInline(admin.TabularInline):
    model = Phone

class ProfileAdmin(admin.ModelAdmin):
    inlines = [
        PhoneInline,
    ]

admin.site.register(Profile, ProfileAdmin)

Now, you can go to the admin interface and try to add a new profile. You will see that you can add multiple phones per profile. I hope it helps you...

Finally, i'll recommend you to take a tour on django's tutorials. You will understand a lot of things and you will get a good idea of how to work with it.

Upvotes: 3

Related Questions