views:

109

answers:

2

I get really confused with many-to-many database relationships, so can some one please clarify how I would achieve this?

I need a table of "Tags" (as in tag words) and a table for "Entries", such at many "Entries" could correspond to many Tag words.

Right now I have my models like this:

# models.py
class Tags(models.Model):
    tag     = models.CharField(max_length=255)
    entry  = models.ManyToManyField(Entry)

class Entry(models.Model):
    entry    = models.CharField(max_length=255)
    description = models.TextField()

Now I'm confused, how would I setup my admin.py so I could then add tags when I create a new entry?

A: 

You will need something along the lines of:

# admin.py

from django.contrib import admin
from models import *

class TagsInline(admin.TabularInline):
    model = Tag
    extra = 1

class EntryAdmin(admin.ModelAdmin):
    inlines = (TagsInline, )

admin.site.register(Entry, EntryAdmin)
admin.site.register(Tag)

(Note, this code was written in a browser!)

Matthew Schinckel
that's what I had actually, and I kept getting:Exception: <class 'testProject.entries.models.Tags'> has no ForeignKey to <class 'testProject.entries.models.entry'>
KeyboardInterrupt
+1  A: 

What you need is using the through feature of models:

class Tags(models.Model): tag = models.CharField(max_length=255) entry = models.ManyToManyField(Entry, through='TaggedEntries')

class Entry(models.Model): entry = models.CharField(max_length=255) description = models.TextField()

class TaggedEntries(models.Model): entry = models.ForeignKey(Entry) tag = models.ForeignKey(Tag)

and now use that model in your admin:

class TagsInline(admin.TabularInline): model = TaggedEntries extra = 1

class EntryAdmin(admin.ModelAdmin): inlines = (TagsInline, )

admin.site.register(Entry, EntryAdmin) admin.site.register(Tag)