本文介绍了如何定义两个字段“唯一”作为夫妇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Django中定义几个字段是唯一的?



我有一张卷(期刊)表,我不想要更多然后是同一个日志的一个卷号。

  class Volume(models.Model):
id = models.AutoField (primary_key = True)
journal_id = models.ForeignKey(Journals,db_column ='jid',null = True,verbose_name =Journal)
volume_number = models.CharField('Volume Number',max_length = 100)
comments = models.TextField('Comments',max_length = 4000,blank = True)

我试图把 unique = True 作为字段 journal_id volume_number ,但它不起作用。

解决方案

有一个简单的解决方案称为,它完全符合您的要求。



例如:

  class MyModel(models .Model):
field1 = models.CharField(max_length = 50)
field2 = models.CharField(max_length = 50)

class Meta:
unique_together = 'field1','field2',)

在你的情况下:

  class Volume(models.Model):
id = models.AutoField(primary_key = True)
journal_id = models.ForeignKey(Journals,db_column ='jid',null = True,verbose_name =Journal)
volume_number = models.CharField('Volume Number',max_length = 100)
comments = models .TextField('Comments',max_length = 4000,blank = True)

class Meta:
unique_together =('journal_id','volume_number',)


Is there a way to define a couple of fields as unique in Django?

I have a table of volumes (of journals) and I don't want more then one volume number for the same journal.

class Volume(models.Model):
    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

I tried to put unique = True as attribute in the fields journal_id and volume_number but it doesn't work.

解决方案

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

这篇关于如何定义两个字段“唯一”作为夫妇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 19:19