如果我创建了两个box objects
(名称相同且用户不同),则会出现MultipleObjectsReturned at /username/slug/
get() returned more than one Box -- it returned 2!
错误。
我还尝试过滤框对象box = Box.objects.filter(user=user, slug=slug)
,但我得到的结果相同。
模型
User = settings.AUTH_USER_MODEL
BOX_REGEX = '^[a-zA-Z0-9 ]*$'
class Box(models.Model):
user= models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
box_name= models.CharField( max_length=100,
validators=[RegexValidator(
regex=BOX_REGEX,
message='Box must only contain Alpahnumeric characters',
code='invalid_box_title'
)],)
slug = models.SlugField(max_length=100, blank=True)
class Meta:
unique_together = ('user', 'slug')
查看
def boxView(request, username=None, slug=None):
user = get_object_or_404(User, username=username)
box = get_object_or_404(Box, user=user, slug=slug)
template = "pages/canvas.html"
context = {'user' : user,'box': box,}
return render(request, template, context)
网址
url(r'^(?P<username>[\w]+)/(?P<slug>[\w-]+)/$', boxView, name='box'),
答案 0 :(得分:0)
你们一起尝试独一无二,但是你们需要的是独一无二的,
class Box(models.Model):
....
class Meta:
unique_together = ('user', 'box_name')
和slug对盒子名称什么都不做,为什么要使用呢?我认为只需将它删除或保持slug与盒子名称相同更好