2

The model I'm using at the moment essentially has three classes. A root class, a tree attached to the root class and a leaf node class that can be attached anywhere in the tree.

e.g. Shop/Category/Product or Shop/Category/Category/Product

Product can only be linked to category. Category can either be linked to another category or shop.

I would use a generic foreign key to link the category to the shop or another category, but as Category is a tree it needs a TreeForeignKey field. I'm looking for example of how this can be done in models.py or an alternative way of achieving the same thing.

Calum
  • 41
  • 1

1 Answers1

0

You don't need a GenericForeignKey for this.

Implement your mptt fk's as normal and use that for setting up the category trees and add an optional shop FK field to link to shops.

from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Shop(models.Model):
    name = models.CharField(max_length=50)

class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    shop = ForeignKey(Shop, null=True, blank=True)

class Products(models.Model):
    name = models.CharField(max_length=50)
    category = models.ForeignKey(Category)
dting
  • 38,604
  • 10
  • 95
  • 114
  • Wouldn't this result in a redundancy with the shop ForeignKeyField? Say you had 10000 categories, only a few would contain a shop ForeignKey. Also is ForeignKeyField a typo? From a naive perspective I thought that the idea of a GenericForeignKey is to replace having to have multiple (partially redundant) foreign keys. – Calum Apr 24 '11 at 14:50