有没有办法在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
中,但它不起作用。
答案 0 :(得分:529)
有一个名为unique_together的简单解决方案可以完全满足您的需求。
例如:
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',)
答案 1 :(得分:6)
将UniqueConstraint
与constraints
选项一起使用。它提供的功能比 if (has_post_thumbnail( $loop->post->ID ))
$thumbnail = get_the_post_thumbnail_url($loop->post->ID,'medium');
endwhile;
//print_r($thumbnail);
//exit();
if($product_count!=0){
?>
<li class="product cg-product-wrap post-1353 page type-page status-publish hentry">
<a href="<?php echo get_term_link( $term->term_id, 'product_tag' ); ?> " >
<div class="cat-pic">
<div class="imagewrapper"><img class="lazy-loaded" src="<?php echo $thumbnail; ?>" data-lazy-type="image" data-src="<?php echo $thumbnail; ?>" alt="Buzos" width="122" height="122" style="width:100%; height:auto;"><noscript><img src="<?php echo $thumbnail; ?>" alt="Buzos" width="122" height="122" style="width:100%; height:auto;" /></noscript></div>
<div class="cat-title">
<h3>
<?php
echo $term->name;
?>
</h3>
</div>
</div>
</a>
</li>
<?php } } ?>
</ul>
</div>
</div>
</div>
(将来可能会弃用)更多。
例如:
unique_together