How to write test case for a Django model which has all the fields as foreignkey in DRF?

Viewed 49

I have a model which has all the fields as a foreign key to other models. How can we create test case in Django rest framework in that case??

I have a model as follows:

class Example(models.Model):

    package = models.ForeignKey(
        Destination, related_name="packages", on_delete=models.CASCADE
    )

    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True,
        related_name="user_packages",
    )

    tour = models.ForeignKey(
        Tours,
        on_delete=models.CASCADE,
        null=True,
        related_name="tour_packages",
    )

In a model, when there is just one field in a Django model, it can be done in the following way:

class NewsLetter(models.Model):
         NewsLetterID = models.AutoField(primary_key=True)
         Email = models.CharField(max_length=255)
         Connected = models.BooleanField(default=False)
         UserID = models.ForeignKey(User, on_delete=models.CASCADE)
         class Meta:
              db_table = 'NewsLetter'

@classmethod
def setUpTestData(cls):
    #Set up non-modified objects used by all test methods
    user = User.objects.create(<fill params here>)
    NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=user)

So even if I have created all the objects for all the foreign-key fields just like this example, the thing is, for the related field models, they themselves have foreign key fields. How can we approach this?? For example in my Example model, the Destination model is itself related to other foreign key fields. So how to create unit test for create api for this Example model??

1 Answers

I think you are approaching this correctly: You will have to setup all required test instances in the right order and link them appropriately.

To make this less cumbersome and more readable, you could use a project like factory_boy to generate fixture factories. Your setup could then look something like this:

import factory

# Define your factories
class PackageFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = 'yourapp.Package'

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = 'yourapp.User'

class TourFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = 'yourapp.Tour'

class ExampleFactory(factory.django.DjangoModelFactory):
    package = factory.SubFactory(PackageFactory)
    user = factory.SubFactory(UserFactory)
    tour = factory.TourFactory(TourFactory)

    class Meta:
        model = 'yourapp.Example'

# And now, create a new example instance together with all related models.
example = ExampleFactory()

# Or create some of them separately and pass them into the factory.
package = PackageFactory()
example = ExampleFactory(package=package)
Related