django 数据库模型
数据库查询操作
try:
a = User.objects.get(email=email).first()
a.vcode = '我很好'
a.save()
except User.DoesNotExist:
raise forms.ValidationError(_("该邮箱账户不存在"))
jieguo = Question.objects.all()
jieguo = Question.objects.filter(name='我很好')
for b in jieguo:
print(f"内容: {b.question_text}, 时间: {b.pub_date}")
user = User.objects.filter(email=email).first()
User.objects.filter(email=email).exists()
from django.db.models import Q
shangpins = Shangpin.objects.filter(Q(diqu='cn') | Q(diqu='ty'))
shangpins = Shangpin.objects.filter(Q(name='哇哈哈') & Q(leixing='饮料'))
dingdans = Dingdan.objects.filter(zhuangtai='dd').exclude(bizhong='BTC')
数据库操作
from myapp.models import Choice, Question
from django.utils import timezone
q = Question(question_text="你好", pub_date=timezone.now())
q.save()
q.uestion_text
q.uestion_text = "你好呀"
q.save()
q.delete()
Gouwuche.objects.create(user=request.user, sku=sku_id, number=1)
Gouwuche.objects.filter(user=request.user).delete()
Usdtqianbao.objects.filter(dizhi=chuzhidd.shoukuanqianbao).update(zhanyong=True)
模型设置外键
class Dingdanmx(models.Model):
dingdan = models.ForeignKey(Dingdan, on_delete=models.CASCADE, related_name='dingdanmxs')
sku = models.ForeignKey(Sku, on_delete=models.CASCADE)
number = models.SmallIntegerField()
jine = models.DecimalField(max_digits=25, decimal_places=15)
jieshouzhanghao = models.CharField(max_length=255, null=True)
neirong = models.CharField(max_length=255, null=True)
xiadanid = models.CharField(max_length=255, null=True)
jieguo = models.BooleanField(null=True)
模板中遍历外键
{% for dingdanmx in dingdan.dingdanmxs.all %}
<small class="is-size-7">{{ dingdanmx.id }}
{% if dingdanmx.jieshouzhanghao %}
({{ dingdanmx.jieshouzhanghao }})
{% endif %}
</small>
{% endfor %}