实现4列复合外键

时间:2018-06-28 06:30:40

标签: django composite-primary-key composite-key

我已经查看了文档并按照[https://pypi.org/project/django-composite-foreignkey/][1]的说明安装了模块,但我正努力实现此目标,如果以下内容正确,则会收到错误消息:“ get()返回了多个错误样本-返回217!”因此,很明显,多键仅作用于一列。我猜测问题在于post = get_object_or_404(Samples, pk=pk)仅返回一个变量,而不是列表/字典?非常感谢您的帮助,因为我需要在实地工作时为考古考察做好准备。

我的view.py

def editsample(request, pk):
    post = get_object_or_404(Samples, pk=pk)
    if request.method == "POST":
        form = SamplesForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            return redirect('allsamples')
        else:
        form = SamplesForm(instance=post)
    return render(request, 'samples/create_samples.html', {'form': form})

我的模型。py:

class Container(models.Model):
    #columns for composite fkey
    area_easting = models.IntegerField()
    area_northing = models.IntegerField()
    context_number = models.IntegerField()
    sample_number = models.IntegerField()
    container_name = models.CharField(max_length=50, blank=True, null=True)
    container_type = models.CharField(max_length=50, blank=True, null=True)
    #foreign keys
    location_id = models.ForeignKey(Location, db_column='location_id', on_delete = models.PROTECT)
    icon_desc = models.ForeignKey(Icon, db_column='icon_desc', on_delete = models.PROTECT)


def __str__(self):
    return self.container_name

class Meta():
    managed=False
    db_table = 'samples\".\"container'
    unique_together = [('area_easting', 'area_northing', 'context_number', 'sample_number'),]


class Samples(models.Model):
    #Composite Key
    area_easting = models.IntegerField()
    area_northing = models.IntegerField()
    context_number = models.IntegerField()
    sample_number = models.AutoField(primary_key=True)

    #other columns
    material = models.CharField(max_length=25)
    ...

#VirtualField
#necs = CompositeOneToOneField(
nesc = CompositeForeignKey(
    Container,
    on_delete=DO_NOTHING,
    #related_name='containers',
    related_name='samples',
    to_fields={
        "area_easting": "area_easting",
        "area_northing": "area_northing",
        "context_number": "context_number",
        "sample_number": "sample_number" })

def __int__(self):
    return self.sample_number

class Meta:
    db_table = 'samples\".\"samples'
    managed = False
    unique_together = (('area_easting', 'area_northing', 'context_number', 'sample_number'),)

0 个答案:

没有答案