我有这个模型,我想制作一个在auth_user DB中注册了用户名的购物清单,他可以创建一个list_name和一个sohppinList,即下面。 我很有趣如何在它们之间建立联系。 有人可以帮帮我吗?
class Item(models.Model):
username = models.ManyToManyField(User)
list_name = models.CharField(max_length=200)
class ShoppingList (models.Model):
list_name = models.ManyToManyField(Item)
item = models.CharField(max_length=200)
quantity = models.IntegerField(default=0)
checkbox = models.BooleanField(default=False)
答案 0 :(得分:0)
我宁愿用这种方式设计模型:
class ShoppingList (models.Model):
user = models.ForeignKey(User,related_name="user_shoplist")
list_name = models.CharField(max_length=200)
# your other fields...
class Item(models.Model):
from_list = models.ForeignKey(ShoppingList, related_name="list_items")
item_name = models.CharField(max_length=200)
# more fields..
#user actions
user = request.user
user_shoplist = user.user_shoplist.create(list_name="Dolls")
#adding items to shopping list
new_item1 = user_shoplist.list_items.create(item_name='barbie')
new_item2 = user_shoplist.list_items.create(item_name='teddy')
#.... etc etc
# all shopping lists of a user
user_shopping_lists = user.user_shoplist.all()
#all items in a shopping list of a user ("user_shoplist" from above)
all_items_in_a_shoppinglist = user_shoplist.list_items.all()
希望,这有助于
更新:你需要在保存过程中将shoplist对象添加到Item对象中。
def create(request):
if request.method == 'POST':
form = ItemForm(request.POST)
if form.is_valid():
# the shoplist object
form.save(commit=False)
form.cleaned_date['from_list'] = your_shoplist_object
form.save()
#...
#...
答案 1 :(得分:0)
你正朝着正确的方向前进。但似乎有些事情有些混乱。如果我试图创建由用户拥有并包含项目的购物清单,我会这样做:
class ShoppingList (models.Model):
user = models.ForeignKey(User, related_name='shopping_lists')
name = models.TextField()
class Item(models.Model):
name = models.TextField()
list_name = models.ForeignKey(ShoppingList, related_name='items')
这可以让你在代码中使用这样的模型:
sl = ShoppingList(user=request.user, name='Christmas Shopping List')
sl.save()
for name in ('socks', 'coal', 'glow sticks'):
sl.items.append(Item.objects.create(name=name))
然后你可以在这样的控制台中使用你的用户:
for s_list in user.shopping_lists.all():
print s_list.items