在运行时更改模型字段

时间:2015-08-11 07:43:25

标签: python django django-models django-orm

我有一些模特:

from salesforce.models import SalesforceModel

class Task(SalesforceModel):
    card = models.CharField(max_length=32)
    who = models.ForeignKey(Lead) # here may be Lead or Contact model ID

和一些更新数据的函数:

def set_contact(contact):
    ...
    # Trying to change
    Task.who = models.ForeignKey(Contact)
    # Or so:
    Task._meta.get_field('who').to = Contact
    task = Task.objects.get(...)
    task.who = contact

ofcourse django不允许改变价值。

ValueError: Cannot assign "Contact: Some Contact": "Task.who" must bea "Lead" instance.

1 个答案:

答案 0 :(得分:0)

Django在运行时构建它的模型,并且在此之后不允许你改变它们。

你有没有看过django_polymorphic

from polymorphic import PolymorphicModel

class ContactBase(PolymorphicModel):
    ...

class Contact(ContactBase):
    ...

class Lead(ContactBase):
    ...

class Task(models.Model):
    card = models.CharField(max_length=32)
    who = models.ForeignKey(ContactBase)

或者Django's generic foreign key

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Task(models.Model):
    card = models.CharField(max_length=32)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

这些解决方案中的任何一个都允许您将多个模型附加到Task,但我发现可以使用Polymorphic route cleaner。