我正在开发我的第一个Django应用程序,并希望创建一个脚本来将数据填充到我的模型中,用于测试目的,类似于使用Django使用Tango时所做的那样。(http://www.tangowithdjango.com/book/chapters/models.html#creating-a-population-script)
我知道如何填充大多数模型字段,但我正忙于填充许多字段。最好的办法是什么?在
from django.db import models
# Create your models here.
class Genre(models.Model):
name = models.CharField(max_length=20, unique=True, blank=False)
def __unicode__(self):
return self.name
class Artist(models.Model):
name = models.CharField(max_length=50, unique=True, blank=False)
photo = models.ImageField(upload_to='artist_photos', blank=True)
logo = models.ImageField(upload_to='artist_logos', blank=True)
genre = models.ManyToManyField(Genre)
twitter = models.URLField(blank=True)
facebook = models.URLField(blank=True)
instagram = models.URLField(blank=True)
def __unicode__(self):
return self.name
class Venue(models.Model):
name = models.CharField(max_length=50, unique=True, blank=False)
logo = models.ImageField(upload_to='venue_logos', blank=True)
capacity = models.IntegerField(blank=False)
address = models.CharField(max_length=50, blank=True)
city = models.CharField(max_length=50, blank=True)
state = models.CharField(max_length=50, blank=True)
zip_code = models.IntegerField(max_length=50, blank=True, null=True)
website = models.URLField(blank=True)
twitter = models.URLField(blank=True)
facebook = models.URLField(blank=True)
instagram = models.URLField(blank=True)
def __unicode__(self):
return self.name
class Show(models.Model):
venue = models.ForeignKey(Venue)
date_time = models.DateTimeField(blank=False)
attendance = models.IntegerField(blank=False)
bands = models.ManyToManyField(Artist)
许多管理者的add方法能够获取多个模型或id:
或者
^{pr2}$所以你可以重写你的方法:
如果要在add_artist函数中添加流派,请将流派作为列表传入,然后将它们添加到多对多字段中,如下所示:
更多信息请参见docs
您应该阅读fixtures上的文档,因为您不需要使用脚本来执行此操作。将名为
m2m
的多对多字段添加到文档中的示例中如下所示:您将看到m2m字段只接受主键列表作为参数。在
相关问题 更多 >
编程相关推荐