我試圖結合this答案和這個one,與一些for循環。在Django中自動生成一組通用多對多字段?
在創建角色時,我想添加所有可能的技能值爲0,但我對如何遵循上述答案感到困惑。
我有這樣的mixin:
class CrossCharacterMixin(models.Model):
cross_character_types = models.Q(app_label='mage', model='mage')
content_type = models.ForeignKey(ContentType, limit_choices_to=cross_character_types,
null=True, blank=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
abstract = True
(最終爲cross_character_types
將擴大)
而這一模式:
class CharacterSkillLink(Trait, CrossCharacterMixin):
PRIORITY_CHOICES = (
(1, 'Primary'), (2, 'Secondary'), (3, 'Tertiary')
)
skill = models.ForeignKey('SkillAbility')
priority = models.PositiveSmallIntegerField(
choices=PRIORITY_CHOICES, default=None)
speciality = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
spec_string = " (" + self.speciality + ")" if self.speciality else ""
return self.skill.skill.label + spec_string
我已經開始寫入此,在NWODCharacter模型上:
def save(self, *args, **kwargs):
if not self.pk:
character_skills_through = CharacterSkillLink.content_object.model
CharacterSkillLink.objects.bulk_create([
[character_skills_through(skill=SkillAbility(
skill), content_object=self) for skill in SkillAbility.Skills]
])
super(NWODCharacter, self).save(*args, **kwargs)
這不起作用,因爲我不認爲我傳遞了正確的對象。在此基礎上answer雖然
:
from django.db import models class Users(models.Model): pass class Sample(models.Model): users = models.ManyToManyField(Users) Users().save() Users().save() # Access the through model directly ThroughModel = Sample.users.through users = Users.objects.filter(pk__in=[1,2]) sample_object = Sample() sample_object.save() ThroughModel.objects.bulk_create([ ThroughModel(users_id=users[0].pk, sample_id=sample_object.pk), ThroughModel(users_id=users[1].pk, sample_id=sample_object.pk) ])
在這種情況下,什麼是我的ThroughModel
?是CharacterSkillLink.content_object.model
?
我如何在我的場景中做到這一點?我很抱歉,如果這是微不足道的,但我正在努力讓我的頭腦。
downvoter讓我知道如何改善這個問題? – Pureferret 2015-02-11 15:35:29