Skip to main content

Django import fixtures IntegrityError: Problem installing fixtures:

IntegrityError: Problem installing fixtures: The row in table 'geonames_alternatename' with primary key '1830' has an invalid foreign key: geonames_alternatename.locality_id contains a value '109436' that does not have a corresponding value in geonames_locality.geonameid.

In a situation where a third party app data export works just fine but the fixutre fails due to any IntegrityError is most likley cause by an overiden `objects` manager that returns only a subset. The solution is to explicitly tell django to export using the default model managers using the `--all` argument for example like so:

dumpdata geonames --indent=4 --all --settings=settings_development > geonames_ext/fixtures/initial_data.json

This is clearly a situation where explicit is better then implicit, that is when defining custom model managers do not touch the `get_query_set` method rather instead add an explict method; for post completeness below is my Eclipse PyDev template I utlize when defining new models.

from django.db import models
#from django.contrib.db import models
from django.core.urlresolvers import reverse
from django.core.urlresolvers import NoReverseMatch
from djanfrom django.utils.encoding import iri_to_uri
from django.utils.http import urlquote
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator, RegexValidator

class ${model_name}Manager(models.Manager):
    Additional methods / constants to ${model_name}'s objects manager:
    ``${model_name}Manager.objects.public()`` - all instances that are asccessible through front end
 ### Model (db table) wide constants - we put these and not in model definition to avoid circular imports.
    ### One can access these constants through .objects.STATUS_DISABLED or ImageManager.STATUS_DISABLED
        (STATUS_DISABLED, "Disabled"),
        (STATUS_ENABLED, "Enabled"),
        (STATUS_ARCHIVED, "Archived"),
 ### We keep status field and custom queries naming a little different as it is not one-to-one mapping in all situations
 ### Note: workarrund -
    QUERYSET_PUBLIC_KWARGS = {'status__gte': STATUS_ENABLED} # because you can't yet chain custom manager filters ex.: 
                                                             # 'public().open()' we provide access the QUERYSET_KWARGS
    def public(self):
        """ Returns all entries someway accessible through front end site"""
        return self.filter(**self.QUERYSET_PUBLIC_KWARGS)   # def active(self):
 # """ Returns all active entries, for example entries that can be selected in forms, searched on, etc""
 #def active(self)
 # return self.filter(status=self.STATUS_ENABLED) 

class ${model_name}(models.Model):
    Main entity representing ${model_name} object
    ### model options - "anything that's not a field"
    class Meta:
        ordering = ['order', 'name']
        get_latest_by = 'order'
        #order_with_respect_to = 
        #permissions = [["can_deliver_pizzas", "Can deliver pizzas"]]
        #unique_together = [["driver", "restaurant"]]
        #verbose_name = "pizza"
        #verbose_name_plural = "stories"
    ### Python class methods
    def __unicode__(self):
  """ Retruns a unicode representation for the instance of this model """
  if settings.DEBUG:
   return u'PK%s: %s - %s' % (,, self.FOO)
  return u'%s - %s' % (,  self.FOO)
    ### Django established method
    #def get_absolute_url(self):
    #    """ Returns the relative url mapping for the instance of this model if it exists or None otherwise"""
    #    return iri_to_uri(reverse('Company', kwargs={'pk':, 'slug': urlquote(slugify(self.__uniocode__()))}))
    #    return reverse ('${model_name}', kwargs={'slug': self.slug})
    def save(self, *args, **kwargs):
        if self.project: # enforce that company matches project's company
        super(Login, self).save(*args, **kwargs) # Call the "real" save() method.        

    def clean(self):
        """ Check if icon is needed or not """
        if self.project and ( !=
            raise ValidationError('Project must belong to the company specified.')
    ### extra model functions
    def get_next_order():
        """ Returns the next available integer for the order field """
            return ${model_name}.objects.latest('order').last + 1
            return 1
    def get_upload_path(instance, filename):
        """ returns a dynamic path for filefields/imagefieds """
        return '%s/%s/%s' % (instance._meta.app_label, instance._meta.module_name, filename)
    def get_geopoint_srid4326(self):
        Returns a geopoint in spatial projection 4326 which is lat and lng coordinate system. 
        We are doing this so we can utilise lat lng in the template as sqlite dosen't support
        all distance calculations in 4326 so we used srid 900913 which is not lat lng based.
        pnt = GEOSGeometry(self.geopoint.wkt) # we have to make copy of point as transform 
        pnt.set_srid(self.geopoint.get_srid())                                      # works in place and dosen't return a new point
        return pnt.transform(4326)
    ### custom managers
    objects = ${model_name}Manager()
    #objects = models.GeoManager() # geodjango objects manager
    ### model DB fields
    # add  blank=False, default='' if you don't want to display a 'blank choice' when rendering modelchoicefield
    status = models.IntegerField(blank=False, default=None, choices=${model_name}Manager.STATUS_CHOICES, default=${model_name}Manager.STATUS_ENABLED)
    order = models.PositiveIntegerField(help_text='Display order modifier, leave default if unsure', unique=False, default=get_next_order, validators=[MinValueValidator(1)])
    name = models.CharField(help_text='Name', max_length=20)
    # rather than database slug use PK and a dynamic slug from name, links will still work using ID lookup
 #slug = models.SlugField(help_text='A short label used in URL generation containing only letters, numbers, underscores or hyphens; hyphens being preferred for SEO optimizations',
 #           unique=True, null=True, validators=[RegexValidator(r'.+')])
    description = models.TextField(help_text='Optional HTML allowed description', blank=True)
    # content = models.TextField(help_text='Optional content', blank=True) # this is not needed keep it simple
    phone = models.CharField(help_text='Main phone number ex. 613-333-4444.', max_length=12, 
                           message="Please enter phone number in following format: 613-333-4444", 
                           code="Unrecognized Phone"))
 services = models.ManyToManyField(LawyerService, limit_choices_to= {'status',}, 
                    help_text='Available Family law services.')
    ### GeoDjango-specific fields
    #geopoint = models.PointField()

As always, if this has hepled you say thank you by commeting or following me on twitter.


Popular posts from this blog

Storing passwords in PuTTY

How to save SSH username/password for auto login in PuTTy The answer is you can't do least in plain PuTTy. However there is an awesome fork with that let's you store the username and password and other additional features called KiTTy.

So grab yourself a copy and +1 this if you do, thanks.

Duplicate value found: duplicates value on record with id: <unknown>.

System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>.The above error is triggered in the database layer and caused by a trigger or workflow outside of your main code of block that is bubbling this exception. This is rather difficult to track down especially if you are unfamiliar with the code, I am sharing my procedure in the hopes this saves you time - if you find this helpful drop me a line or follow me on twitter @danielsokolows. This error is caused by unique field constraint on the object, so the first step is to examine the object and locate the API names of all unique fieds. You can do this through SF direclty 'Setup < Customize &lt <object being inserted> &lt Fields' or by downloading the `src/objects` metadata information and searching for <unique>; I preffer the latter and actually download ALL matadata information f…

Softeher 'Error occurred. (Error code: 2)' sollution

Protocol error occurred. Error was returned from the destination server.The Softether server by default to run on port 443, if you server also hosts normal https then 443 is already taken and so Softether can't bind to it. When you run `vpncmd` it attempts to connect, find an active port, but of course fails with 'Protocol error occurred. Error was returned from the destination server.' because it's not actually connecting to the vpn server. By default Softether also listens on 992, 1194, and 5555 so the sollution is to modify specify `localhost:5555` when executing the `vpncmnd`. If this has helped you feel free to comment or follow me on twitter @danielsokolows.