Is it possible to use django-mptt and GenericForeignKey?
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.
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)
精彩评论