title: Create Django Model Object Instance Without DB Lookup For Foreign Keys
body: <p>I have a use case where I want to be able to create instances of model objects that have foreign key constraints to other models.</p>
  
  <p><code>models.py</code></p>
  
  <pre><code>from django.db import models
  
  class Foo(models.Model):
  
      __module__ = "some_app"
      foo_name = models.CharField(null=False, blank=False,
                                  unique=True, max_length=50)
  
      def __str__(self):
          return self.foo_name
  
  
  class Bar(models.Model):
  
      __module__ = "some_app"
      bar_name = models.CharField(null=False, blank=False,
                              unique=True, max_length=50)
  
      def __str__(self):
          return self.bar_name
  
  class FooBar(models.Model):
  
       __module__ = "some_app"
       version = models.IntegerField(null=False, blank=False)
       foo = models.ForeignKey(Foo, on_delete=models.CASCADE)
       bar = models.ForeignKey(Bar, on_delete=models.CASCADE)
  
      def __str__(self):
          return f"{self.foo}@{self.bar}: {self.version}"
  </code></pre>
  
  <p>Say for example I have instances of my <code>Foo</code> and <code>Bar</code> classes.</p>
  
  <pre><code>a_foo = Foo(foo_name="my_foo")
  a_foo.save()
  
  a_bar = Bar(bar_name="my_bar")
  a_bar.save()
  </code></pre>
  
  <p>Some time after they've been created, I know what the names are, but I don't have references to the objects. Similarly I don't know their ids. But I do want to use them to create an instance of <code>FooBar</code>. I can create that instance by doing this</p>
  
  <pre><code>foo = get_object_or_404(Foo, foo_name="my_foo")
  bar = get_object_or_404(Bar, bar_name="my_bar")
  foo_bar = FooBar(foo=foo, bar=bar, version=1)
  </code></pre>
  
  <p>But would like to avoid having to make two unnecessary DB calls to create, instances of the objects. Or even just to look up their ids. What I'd prefer to do is something like this</p>
  
  <pre><code>foo_bar = FooBar(foo__foo_name="my_foo", bar__bar_name="my_bar", version=1)
  </code></pre>
  
  <p>Then have the DB return an error if the corresponding objects don't exist (or aren't unique). Is there a way to this?</p>