我正在学习Django并寻找最佳实践:
想象一下,我有一个移动电话设备的型号:
class Device(models.Model):
vendor = models.CharField(max_length=100)
line = models.CharField(max_length=100, blank=True)
model = models.CharField(max_length=100)
让我们说我创建了这样一个对象:
Device.objects.create(vendor = "Apple",
line = "iPhone",
model = "SE"
)
或没有" line":
Device.objects.create(vendor = "Xiaomi",
model = "Mi 6"
)
然后,我想跟踪每个设备在我店里的销售情况,因此我创建了一个" Deal" (我只跟踪交易日期和销售的设备,设备作为ForeignKey):
class Deal(models.Model):
device = models.ForeignKey(Device, on_delete=models.CASCADE)
deal_date = models.DateTimeField(default=None)
问题: 什么是创建"交易"的最佳方式?对象,如果我想查询"设备"以其完整的连接名称,例如, " Apple iPhone SE"或者"小米米6"? 我在Django database entry created by concatenation of two fields中发现了类似的内容,但不确定它是否适合我的正确道路。
我最好的猜测是这样的(其中"名称"是连接字段):
de = Device.objects.get(name = "Apple iPhone SE")
Deal.objects.create(device = de,
deal_date = datetime(2018, 4, 26, 15, 28)
)
执行此任务的正确方法是什么?非常感谢你的帮助!
答案 0 :(得分:0)
假设var name
包含您的文本搜索条件并使用您的数据模型,您可以使用annotation
为查询集返回的每个对象创建一个字段,然后使用此进行过滤字段
您可以尝试以下(未经测试)
import datetime
from django.db.models import F
from your.app.models import Deal, Device
# supposing is in your view, but like sounds as a model method
def my_view(request, *args, **kwargs)
name = request.POST.get('name')
device_qs = Decive.objects.all().annotate(text_concatenated='{} {} {}'.format(F('vendor'), F('line'), F('model'))).filter(text_concatenated=name)
try:
device = device_qs.get()
except Device.DoesNotExist:
# to manage the scenario when doesn't exist any match
# here you manage this situation
pass
except Device.MultipleObjectsReturned:
# to manage the scenario when various devices have the same 'text concatenated', i dont know, maybe data model should be improved
# here you manage this situation
device = device_qs.first()
deal = Deal.objects.create(device=device, deal_date=datetime.datetime.now())
# build your response and return it
答案 1 :(得分:0)
感谢您的建议,多多搜索一下,我找到了适合我的答案:
我做的是我调整了save()
方法,现在自动填充一个字段作为其他3个字段的串联。
@property
在这种情况下也很有用