我在数据库中有一个现有条目,我想检查我的views.py,如果该条目已存在于数据库中,如果确实如此,那么新值将替换该行中的旧数据,否则创建一个该用户的新行。我怎么能这样做?
#models.py
class Member(models.Model):
username = models.CharField(max_length=16, primary_key=True)
password = models.CharField(max_length=16)
profile = models.OneToOneField(Profile, null=True)
following = models.ManyToManyField("self", symmetrical=True)
class Message(models.Model):
user = models.ForeignKey(Member, related_name='%(class)s_user')
recip = models.ForeignKey(Member, related_name='%(class)s_recip')
pm = models.BooleanField(default=True)
time = models.DateTimeField()
text = models.CharField(max_length=4096)
def __str__(self):
return self.username
#forms.py
class UploadFileForm(forms.ModelForm):
class Meta:
model = ProfilePic
fields = ['text','thumbnail']
#models.py
class ProfilePic(models.Model):
user = models.ForeignKey(Member, related_name='%(class)s_user', null=True)
text = models.TextField(max_length=4096)
thumbnail = models.FileField(upload_to='media', null=True)
#views.py
if request.POST:
username = request.session['username']
member_obj = Member.objects.get(pk=username)
form = UploadFileForm(request.POST,request.FILES)
profile_pic = form.save(commit=False)
**#checking if username already exists in the DB:**
member_obj = Member.objects.update_or_create(username=username)
**#if yes then replace data in the row with the new one,
# if not create a new row**
profile_pic.user = member_obj
profile_pic.save()
答案 0 :(得分:2)
试试这个,
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
cd = form.cleaned_data
username = request.session['username']
if Member.objects.filter(username=username).exists():
member_obj = Member.objects.get(username=username)
profile_pic = ProfilePic.objects.get(user=member_obj)
profile_pic.user = member_obj
# you can update other fields by using object.field_name (e.g. profile_pic.text = request.POST.get['text']
profile_pic.save()
else:
ProfilePic.objects.create(user=username)
return HttpResponse('success')
else:
return HttpResponse(form.errors)
else:
form = UploadFileForm
答案 1 :(得分:0)
您应该更改查询集:
member_obj = Member.objects.get(pk=username)
到
member_obj = Member.objects.get(username=username)
如果username = request.session['username']
是username
对象的user
属性。如果您使用username
s(而不是id
),则必须强制执行不同的用户名。
如果您想使用pk
(id
),则应将其存储在会话中,然后查询将是:
user_id = request.session['id']
member_obj = Member.objects.get(pk=user_id)
答案 2 :(得分:0)
正如你所做的那样,update_or_create
就是为了这个。但是,您应该按如下方式使用它:
defaults = {} # Here you should specify the values that will be updated on the member object,
# Or the default values to pass to the newly created instance
# Update or create return a tuple (object, created), created being a boolean
member_obj, created = Member.objects.update_or_create(username=username, defaults=defaults)
# This part seems correct to me
profile_pic.user = member_obj
profile_pic.save()