问题
I build an app in django, but since I found out that google app engine doesn't support Django out of the box (free,cloud sql can't be used for free right?).
I decided to move to Django-nonrel, so there are few datebase Field that need converting, and I don't know how:
class Cate(models.Model):
name = models.CharField(max_length = 100)
description = models.TextField()
create_by = models.ForeignKey(User)
create_date = models.DateTimeField('cate created date')
def __unicode__(self):
return self.name
class Product(models.Model):
product_name = models.CharField(max_length = 200)
owner = models.ForeignKey(User)
cate = models.ManyToManyField(Cate)
timestamp = models.DateTimeField('product added date')
view = models.IntegerField(default = 0)
def __unicode__(self):
return self.product_name
here is the user_profile model which extends from user model
class UserProfile(models.Model):
user = models.OneToOneField(User)
cates = models.ManyToManyField('shop.Cate')
the Cate model is created by admin, UserProfile can have many cates, and same cate can belong to many users, same as product.
please help to construct these models and maybe some tips on how to use Django-nonrel
I am really new to database
回答1:
There's two ways to do this. The cheaper version is to use ListFields
from djangotoolbox.fields import ListField
class UserProfile(models.Model):
user = models.OneToOneField(User)
cates = ListField(models.ForeignKey(shop.Cate))
The ListField simply stores a list of Cate ids. There's some important limitations to this.
Your entity is limited to 1MB, so this limits the number of entities in your list. In this case, it'll still be a fairly large number, especially since there's nothing else in your entity.
You can do dataastore queries against the cates field if it's indexed. However, each entity has a limit of 5000 indexes. You'll use one for the user attribute, so in this case, your cates list will be limited to have 5000 entries. I haven't hit this before so I don't know how it would fail, I presume you'd get an exception on writing your entity.
The more expensive option is to use an intermediate mapping entity. This gives you unlimited relations for the extra expense of creating/querying the mapping entities.
class UserCateMapping(models.Model)
user = models.ForeignKey(UserProfile)
cate = models.ForeignKey(Cate)
In this case, you'll need to create a new entity for each relation, and query for the UserCateMapping entities before fetching the actual Cate or UserProfile entity you actually want to use. It's going to be more costly than the first option, but you'll have unlimited mappings.
来源:https://stackoverflow.com/questions/14019445/how-to-convert-django-manytomanyfield-into-django-nonrel-field