Django:很多人

2024-04-27 04:12:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发我的第一个Django应用程序,并希望创建一个脚本来将数据填充到我的模型中,用于测试目的,类似于使用Django使用Tango时所做的那样。(http://www.tangowithdjango.com/book/chapters/models.html#creating-a-population-script

我知道如何填充大多数模型字段,但我正忙于填充许多字段。最好的办法是什么?在

在模型.py在

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)

在填充.py在

^{pr2}$

Tags: name模型selffalsetruemodelmodelsdef
3条回答

许多管理者的add方法能够获取多个模型或id:

ids_list = [1,2,3]
artist.genre.add(*ids_list) # or
artist.genre.add(1,2,3)

或者

^{pr2}$

所以你可以重写你的方法:

def add_artist(name, genres):
  a, created = Artist.objects.get_or_create(name=name)
  a.genre.add(*Genre.objects.filter(name__in=[genres]))

如果要在add_artist函数中添加流派,请将流派作为列表传入,然后将它们添加到多对多字段中,如下所示:

def add_artist(name, genres):
  a, created = Artist.objects.get_or_create(name=name)
  for genre in genres:
     a.add(genre)

更多信息请参见docs

您应该阅读fixtures上的文档,因为您不需要使用脚本来执行此操作。将名为m2m的多对多字段添加到文档中的示例中如下所示:

[
  {
    "model": "myapp.person",
    "pk": 1,
    "fields": {
      "first_name": "John",
      "last_name": "Lennon"
      "m2m": [1,2]
    }
  },
  {
    "model": "myapp.person",
    "pk": 2,
    "fields": {
      "first_name": "Paul",
      "last_name": "McCartney"
      "m2m": [1,2]
    }
  }
]

您将看到m2m字段只接受主键列表作为参数。在

相关问题 更多 >