我正在创建一个django应用程序,用户可以在其帐户中存储多个网址。问题是,我面临的是单个用户能够存储单个网址,在添加多个网址时会出现完整性错误。 那么如何将多个网址添加到单个用户对象
models.py
class Userprofile(models.Model):
user = models.OneToOneField(User)
url = models.CharField(max_length = 100 ,)
shortcode = models.CharField(max_length = 10 ,blank = True)
timestamp = models.DateTimeField(auto_now_add = True)
def save(self , *args , **kwargs):
if self.shortcode is None or self.shortcode is '':
self.shortcode = create_shortcode(self)
super(Userprofile, self).save(*args , **kwargs)
def __str__(self):
return self.user.username
forms.py
class URLForm(forms.ModelForm):
class Meta:
model = Userprofile
fields = ('url',)
widgets={
'url':forms.TextInput(attrs={'placeholder':'Long URL','class':'form-control'}),
}
def clean_url(self):
url = self.cleaned_data['url']
url_validator = URLValidator()
try:
url_validator(url)
except:
raise forms.ValidationError('Enter a proper URL ')
return url
Views.py
def user_url_info(request):
if request.method == 'POST':
form = URLForm(request.POST)
if form.is_valid():
# try:
# obj = Userprofile.objects.get(url = form.cleaned_data['url'])
# print('already')
# except:
obj = form.save(commit = False)
obj.user = request.user
obj.save()
return render(request , 'detaail.html',{'obj':obj})
else:
form = URLForm()
return render(request , 'urlform.html' ,{'form':form})
所以我想要一个request.user可以解决Userprofile的多个对象
答案 0 :(得分:0)
您需要为网址创建模型,并使用网址模型中的外键用户ID进行连接。存储冗余数据意味着数据库未规范化。将数据存储在这个问题中,进行了规范化,充分利用了Django的对象关系模型。
答案 1 :(得分:0)
您可以将url字段设为外键,并创建一个新模型以仅存储url
class UserURL(models.Model):
url = models.CharField(max_length = 100 ,)
class Userprofile(models.Model):
user = models.OneToOneField(User)
url = models.Foreignkey(UserURL)
shortcode = models.CharField(max_length = 10 ,blank = True)
timestamp = models.DateTimeField(auto_now_add = True)
答案 2 :(得分:0)
如果您询问如何将用户与多个网址相关联,则不应该执行OneToOne字段。
class UserUrlRelationship(models.Model):
url = models.CharField(...)
user = models.ManyToManyField(User)
或
class Url(models.Model):
url = models.CharField(...)
class UserUrlRelationship(models.Model):
url = models.ForeignKey(Url)
user = models.ForeignKey(User)
# This is literally what a ManyToManyField does in the background.
# If you investigate the database, you will see extra tables that
# represent your many to many fields. each entry is a relationship. Make sure that you
# don't have unique constraints on these 2 fields via OneToManyFields,
# OneToOneFields or unique=True.
不要对OneToOne字段进行限制,否则会限制您,以便一个用户只能映射到一个URL,而另一个用户只能映射到一个url(一个url只有一个用户)。