1

I am using Django 1.6. In the "Add" interface for one of my models, I have a field that is a foreign key to another model. Therefore it is displayed as a dropdown box containing the string representation of the second model. I want to be able to split it up into its constituent fields instead. Is there a way to do this?

ie. For example, in my "Add" screen for the model for "User", I have a field "Favourite Book". "Book" is displayed as a dropdown menu with string representations "Title, Author" for all books in the database, and I want to be able to display two dropdown menus instead, one for each of the fields Title and Author.

EDIT This isn't my actual application. In my application, there is the added feature that all Author-Title combinations are possible (obviously this is not really the case for this example), so it would be very useful to be able to select the Title and Author separately rather than from a giant drop down menu containing all possible permutations.

kmc
  • 97
  • 6

1 Answers1

0

What you are saying doesn't really make sense. The foreign key dropdown represents all Book objects in your database and allows you to create a relationship between your User and the particular Book that you select, i.e. that particular title/author combination. You can't select title and author independently as they are fields in a single Book and represent that particular Book (not to mention that title is a text field)

You could use a Django Admin Inline. You can see an example of inlines in this question:

enter image description here

This would allow you to relate numerous Books to a single User within the same admin page.

# models.py
from django.db import models

class User(models.Model):
   name = models.CharField(max_length=100)

class Book(models.Model):
   user = models.ForeignKey(User)
   title = models.CharField(max_length=100)

# admin.py
from django.contrib import admin

class BookInline(admin.StackedInline):
    model = Book

class UserInline(admin.ModelAdmin):
    inlines = [
        BookInline,
    ]
Community
  • 1
  • 1
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
  • Thanks for taking the time to answer my question. I probably shouldn't have used that example, as my actual case is a little different. I thought a quick example would at least make things a little more concrete. In my particular application, it is as though every "Author" can have a book with every "Title". All permutations are possible. Therefore it would be very useful to be able to select "Title" and "Author" from their own drop down, rather than searching through a single giant drop down containing all possible combinations (which are all valid and already exist in the database). – kmc May 08 '14 at 12:42