Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6618061
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T20:46:49+00:00 2026-05-25T20:46:49+00:00

I have the following model : class A: b = ForeignKey(‘B’) class B: a

  • 0

I have the following model :

class A:
  b = ForeignKey('B')

class B:
  a = ForeignKey('A', null=True)

I have several methods that decode a json object and create a tree of objects A and B.
Suppose I have an object of type A that I want to save, I’m trying to write something like this

in class A :

def save(self, *args, **kwargs):
  self.b.save()
  super(A, self).save(*args, **kwargs)

in B :

def save(self, *args, **kwargs):
  if self.a:
    self.a.save()
  super(B, self).save(*args, **kwargs)

This does not work, even though A.b and B.a get assigned an id while calling save(), it still violates the not null constraint in A.
I’ve read somewhere that this was due to how ORM works, and how the objects are cached somehow.

The solution proposed was to do something like this :

a = A()
b = B()
b.save()
a.b = b
a.save()

But for obvious reason of recursion, it’s not appropriate in my case. So the only work around I can think of is to provide each objects with a method that recursively retrieve every object that need to be saved, and then do a for loop to save each one in the right order. I really would like to avoid this, since of course the actual model is more complex and involves more than two classes and more than one Foreign Key per class.

So I guess my question is simply : Is there a better way or a more common way to proceed in such situations ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T20:46:50+00:00Added an answer on May 25, 2026 at 8:46 pm

    Well after some soul searching I found out that this was indeed a cache “problem”. I don’t have the time to look inside django code to understand how things really work, so if anyone have some interesting insights that would be great.

    In the meantime, the solution I found is to force the object to clear its cache like this :

    def save(self, *args, **kwargs):
      self.b.save()
      self.b = self.b # yes ...
      super(A, self).save(*args, **kwargs)
    

    This does work, but for the record here is a little helper to automatically clear cache before any saving :

    def clear_cache(obj):
      map(lambda x: obj.__setattr__(x, obj.__getattribute__(x)), \ # force reassignment
        map(lambda x: re.match('_(.*)_cache', x).groups()[0], \    # get attribute name
        filter(lambda x: x.find('_cache') != -1, dir(obj))))       # get all attribute with cache
    
    @receiver(pre_save)
    def cache_callback(sender, instance, **kwargs):
      clear_cache(instance)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following model class DNS(models.Model): domain = models.ForeignKey(Domain) host_start = models.CharField(max_length=150, blank=True,
Let's assume that I have following models: class ScoutBook(models.Model): troop = models.ForeignKey('Dictionary', limit_choices_to={'type' :
I have the following model layout: class A(models.model): options = models.ManyToManyField(OptionSet, blank=True, null=True) values
I have model class CreatedMixin(object): __abstract__ = True @declared_attr def created_by(cls): return Column(Integer, ForeignKey('user.user_id',
I have the the following Django model: class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) full_name
I have following two models class Questionnaire(models.model) name = models.CharField(max_length=128, null=True, blank=True) type =
I have following model: class Client(models.Model): user = models.OneToOneField(DjangoUser, unique=True) address = models.ForeignKey(Address,blank=True) class
hi i have to following model class Match(models.Model): Team_one = models.ForeignKey('Team', related_name='Team_one') Team_two =
Suppose I have the following models: class User(models.Model): pass class A(models.Model): user = models.ForeignKey(User)
I have the following model structure: class Container(models.Model): pass class Generic(models.Model): name = models.CharacterField(unique=True)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.