Задать вопрос

Тел: +7 965 3737 888

504

Просмотров

1

Ответов

Modifying the fields of a third/existing model class

<p>You can extend the class <strong>ModifiedModel</strong> to set new fields, replace existing or exclude any fields from a model class without patch or change the original code.</p>
<p><strong>my_app/models.py</strong></p>
from django.db import models

class CustomerType(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

class Customer(models.Model):
    name = models.CharField(max_length=50)
    type = models.ForeignKey('CustomerType')
    is_active = models.BooleanField(default=True, blank=True)
    employer = models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

<p><strong>another_app/models.py</strong></p>
from django.db import models
from django.contrib.auth.models import User

from this_snippet import ModifiedModel

class City(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

class HelperCustomerType(ModifiedModel):
    class Meta:
        model = 'my_app.CustomerType'

    description = models.TextField()

class HelperCustomer(ModifiedModel):
    class Meta:
        model = 'my_app.Customer'
        exclude = ('employer',)

    type = models.CharField(max_length=50) # Replaced
    address = models.CharField(max_length=100)
    city = models.ForeignKey(City)

    def __unicode__(self):
        return '%s - %s'%(self.pk, self.name)

class HelperUser(ModifiedModel):
    class Meta:
        model = User

    website = models.URLField(blank=True, verify_exists=False)

Вопрос полезен? Да0/Нет0
file_3487.py(2.4Кб)
None

Ответы (1):

Ответielectric:10.09.2011
Ответ полезен? Да0/Нет0

This is pretty nice, does it work with South?